我正在尝试创建一个用于在向量中分割空格的程序,但它不会删除原始字符串的第二部分。
#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';
}
您的代码语法正确,但是由于您使用了对容量改变的向量元素的引用,该代码未能完成任务。
:string &e = words[0]; ... words.push_back(...); ...
std::vector通常用于通过请求连续的内存块来存储数据。当前容量用完((由于插入更多元素而导致的结果)
如果知道向量中要存储的项目总数,则可以set the capacity of the vector in advance避免无效:
。尽管它不支持随机元素访问((非常令人失望);它不需要连续的内存块,也不会造成无效的风险,除非您明确销毁了引用的元素。std::vector<string> words; words.reserve(3); words.push_back("aa bb"); string &e = words[0]; ... words.push_back(...); ...
std::list与
std::vector
不同,被实现为链表
结论
:关于std::vector
中要存储的元素总数的信息可能不容易获得,因此,在需要引用快速扩展容器的元素的情况下,std::list
似乎更可靠。我建议对此任务使用std::list
。
int main()
{
std::list<string> words;
words.push_back("aa bb");
string &e = words.back();
string::iterator a = e.begin(), b;
while (1)
{
b = std::find_if(a, e.end(), [](auto &c){ return (c == ' '); });
words.push_back(string(a, b));
a = std::find_if_not(b, e.end(), [](auto &c){ return (c == ' '); });
if (a == e.end()) break;
}
for(auto &f: words) cout << f << endl;
return 0;
}