ページ 11

String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 14:37
by A new
C++初心者です。
string型の文字を任意の文字で区切る関数を作成しています。
ex) "abc/def" → "abc" "def"

以下のサイトを参考に下のような関数を作成しましたがコンパイルエラーが発生します。
http://vivi.dyndns.org/tech/cpp/string.html

どこが悪いのかご教授お願いできたらと思います。
よろしくお願いいたします。

自作プログラム
#include <iostream>
#include <string>
#include <vector>

//名前空間 自作関数はすべてmfという名前空間に入れることとする
namespace mf{
std::vector<std::string> split();
}

std::vector<std::string> split(const std::string str, char sep){
/*
strをsepで区切ったあとそれらをvector型配列で返す関数
std::vector<データ型>でデータ型のvectorを作成できる
*/

//string型ベクトルを定義
std::vector<std::string> v;
std::string::iterator first, last;

//最初の文字を取得
//std::string::iterator first = str.begin(); //autoはコンパイル時に自動で型を推論してくれる firstはイテレータ
first=str.begin();

while (first != str.end()){ //テキスト内が空になるまでループ
//std::string::iterator last = first;
last = first;
while (last != str.end() && *last != sep){
++last; //イテレータを進める
}
v.push_back(std::string(first, last));

if (last != str.end()){
++last; //分割文字の次へ
}
first = last;
}
return v;
}

Re: String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 14:50
by A new
質問者です。
コードの貼り付けがうまくいっていませんでしたのでもう一度貼り付けさせていただきます。

コード:

#include <iostream>
#include <string>
#include <vector>

//名前空間 自作関数はすべてmfという名前空間に入れることとする
namespace mf{
    std::vector<std::string> split();
}

std::vector<std::string> split(const std::string str, char sep){
    /*
    strをsepで区切ったあとそれらをvector型配列で返す関数
    std::vector<データ型>でデータ型のvectorを作成できる
    */

    //string型ベクトルを定義
    std::vector<std::string> v;
    std::string::iterator first, last;

    //最初の文字を取得
    //std::string::iterator first = str.begin();   //autoはコンパイル時に自動で型を推論してくれる firstはイテレータ
    first=str.begin();

    while (first != str.end()){ //テキスト内が空になるまでループ
        //std::string::iterator last = first;
        last = first;
        while (last != str.end() && *last != sep){
            ++last; //イテレータを進める
        }
        v.push_back(std::string(first, last));  

        if (last != str.end()){
            ++last; //分割文字の次へ
        }
        first = last;
    }
    return v;
}




Re: String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 14:52
by かずま
const std::string str なので、
std::string::iterator first, last; を
std::string::const_iterator first, last; にする。

Re: String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 15:07
by かずま
コメントに auto のことを書いているのだから、
std::string::iterator first, last;
first = str.begin(); を
auto first = str.begin(); に、
last = first; を
auto last = first; にすればよいでしょう。

それから、namespace mf の中には、引数なしの split が宣言され、
定義されている split の方は、引数があり、
namespace mf の中に入っていないので別物です。

Re: String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 15:13
by A new
ご返信ありがとうございます。

指摘していただいた点を書き直したところ、先ほどまで発生したエラーが出現しなくなりました。


お忙しい中ご助言いただきありがとうございました。

Re: String型を任意の文字で区切る関数

Posted: 2017年7月31日(月) 15:25
by かずま
A new さんが書きました: 指摘していただいた点を書き直したところ、先ほどまで発生したエラーが出現しなくなりました。
const_iterator にしたのか、auto にしたのかを書いてください。
また、namespace の問題はどうしたのですか?

フォーラムルール
解決した時は、「解決しました」とだけ言って去らず、ソースコードや解決した方法を明記して下さい。
と書いてあります。