我的意图是拥有一个包含给定字符串的所有子字符串的 vector 。我试图通过将 vector 中的当前字符串与 str
的迭代字符连接起来来推送元素下面的代码出了什么问题。
void Substring(string str)
{
vector<string> vec={""};
for(auto i =0; i<str.length(); i++)
{
auto end = vec.end();
string s(1,str[i]);
for (auto iter = vec.begin(); iter!=end; iter++)
{
vec.push_back(s+ static_cast<string>(*iter)); // --> what is the problem here in concatenation
}
}
for (auto iter = vec.begin(); iter!=vec.end(); iter++)
{
cout <<"iter_val:"<<*iter <<endl; //--> does not print concated element
}
}
最佳答案
vec.push_back
invalidates existing iterators .您可能想更改算法以避免这种情况,例如:
std::vector<std::string> substrings(std::string const& s) {
std::vector<std::string> result;
for(size_t i = 0, j = s.size(); i < j; ++i)
for(size_t k = 1, l = j - i - !i; k <= l; ++k)
result.push_back(s.substr(i, k));
return result;
}
int main() {
for(auto const& s : substrings("abc"))
std::cout << s << '\n';
}
关于c++ - 尝试使用取消引用的迭代器进行连接时,无法在字符串 vector 中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49726610/