次のプログラムでセグメンテーションフォルトが発生しました。
なぜこのようなことが起こり、どうすれば解決できますか?検索は、すべての一致するように文字列からベクトルを作成するプログラムのセグメンテーションフォルト
std::vector<std::string> split_words(std::string s) {
std::vector<std::string> v;
std::regex pattern("[!-~]+");
std::cmatch result;
while(regex_search(s.c_str(), result, pattern)) {
for(auto it : result)
v.push_back(it);
s = result.suffix().str();
}
return v;
}
:
私は思う#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
std::vector<std::string> split_words(std::string s) {
std::vector<std::string> v(1, "");
int i=0;
int wortanzahl = 0;
while(i<s.size()) {
if (s[i]!=' ') {
v.resize(wortanzahl + 1, "");
for (int j=i; s[j]!=' '; ++j) {
v[wortanzahl] += s[j];
i=j;
}
++wortanzahl;
}
++i;
}
}
int main() {
std::string s = "Alpha beta! Gamma";
split_words(s);
return 0;
}
スペースで単語を分割するには、 'std :: istringstream'を使用します。このようなループを作成する必要はありません。 – PaulMcKenzie
デバッグビルドがあることを確認し、デバッガでプログラムを実行してください。セグメンテーションフォルトが発生すると、発生した行とプログラムの状態が表示されます。または、既存のコアファイルを調べることができます。 PS、何も 'j'が終わりを止めるのを止める... – Useless