C++ 分割空白字符串的程序赢得';行不通
我正在尝试制作一个程序来分割向量中的空白字符串,但它不会删除原始字符串的第二部分C++ 分割空白字符串的程序赢得';行不通,c++,vector,c++14,C++,Vector,C++14,我正在尝试制作一个程序来分割向量中的空白字符串,但它不会删除原始字符串的第二部分 #include<iostream> #include<string> #include<string.h> #include<vector> #include<algorithm> #include<cmath> #include<sstream> #include<fstream> #include<list
#include<iostream>
#include<string>
#include<string.h>
#include<vector>
#include<algorithm>
#include<cmath>
#include<sstream>
#include<fstream>
#include<list>
#include<numeric>
#include<map>
#include<iterator>
using namespace std;
int main(){
vector<string> words;
words.push_back("aa bb");
string& e=words[0];
string::iterator it=find(e.begin(),e.end(),' ');
if(it!=e.end()){
words.push_back(e);
e.erase(it,e.end());
string& e2=words.back();
it=find(e2.begin(),e2.end(),' ');;
e2.erase(e2.begin(),it+1);
}
for(auto& f:words)
cout<<f<<'\n';
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
int main(){
向量词;
字。推回(“aa-bb”);
字符串&e=单词[0];
string::iterator it=find(e.begin(),e.end(),“”);
如果(it!=e.end()){
词。推回(e);
e、 擦除(它,例如end());
string&e2=words.back();
it=find(e2.begin(),e2.end(),“”);;
e2.erase(e2.begin(),it+1);
}
用于(自动和自动:文字)
cout您的代码语法正确,但代码未能完成任务,因为您使用了对容量已更改的向量元素的引用
通常通过请求连续的内存块来存储数据。当当前容量用完时(由于插入更多元素):
创建了容量更大的新连续内存块
将旧块中的元素复制到新块中
旧内存块被破坏
存储在旧内存块中的对象的引用、指针甚至迭代器都将无效
如果您知道要存储在向量中的项目总数,可以通过以下方法避免无效:
std::vector<string> words;
words.reserve(3);
words.push_back("aa bb");
string &e = words[0];
...
words.push_back(...);
...
@ohndoeisabro在此语句后面加上单词。推回(e);引用e可能无效。仅供参考,为您完成所有工作。@nonock如果您使用特定版本的c++?
标记,请在主c++
标记之外使用它们(以便更好地查看问题)另外,我在这里没有看到任何C++14特定的内容,也不知道为什么您认为该标记会更适合。在C++14上自动(&O)。
std::vector<string> words;
words.reserve(3);
words.push_back("aa bb");
string &e = words[0];
...
words.push_back(...);
...