首页 > 解决方案 > 拆分空白字符串的程序不起作用

问题描述

我正在尝试制作一个用于在向量中拆分空格字符串的程序,但它不会删除原始字符串的第二部分。

#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';
}

标签: c++vectorc++14

解决方案


您的代码语法正确,但代码未能完成任务,因为您使用了对容量改变的向量元素的引用

string &e = words[0];
...
words.push_back(...);
...

std::vector通常被实现为通过请求连续的内存块来存储数据。当当前容量用完时(由于插入更多元素)

  1. 创建具有更大容量的新连续内存块。
  2. 旧块中的元素被复制到这个新块中。
  3. 旧的内存块被破坏。
  4. 存储在旧内存块中的对象的引用、指针甚至迭代器都变得无效。

如果您知道要存储在向量中的项目总数,则可以提前设置向量的容量以避免失效:

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;
}

推荐阅读