c++ - 拆分空白字符串的程序不起作用
问题描述
我正在尝试制作一个用于在向量中拆分空格字符串的程序,但它不会删除原始字符串的第二部分。
#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通常被实现为通过请求连续的内存块来存储数据。当当前容量用完时(由于插入更多元素):
- 创建具有更大容量的新连续内存块。
- 旧块中的元素被复制到这个新块中。
- 旧的内存块被破坏。
- 存储在旧内存块中的对象的引用、指针甚至迭代器都变得无效。
如果您知道要存储在向量中的项目总数,则可以提前设置向量的容量以避免失效:
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;
}
推荐阅读
- r - GGPlot2:按条件分组的误差线
- python - 在函数中传递列名
- mathematical-optimization - CBC 求解器返回的解是否准确?
- postgresql - PostgreSQL => ALTER TABLE without timezone -> with timezone, using select for TZ
- java - 应用程序关闭后,Android 服务不存在
- c# - 在侦听用户输入时在不同的线程上运行方法
- c - Mini-GMP Arduino 打印
- c - 在 C 中为动态数字输入读取字符串时出现问题
- xamarin - 如何将通知的小图标设置为应用程序的图标?
- java - Java 语言练习与数组