用于分隔空格字符串的程序将不起作用

问题描述 投票:0回答:1

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

#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++ vector
1个回答
0
投票

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

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

std::vector通常用于通过请求连续的内存块来存储数据。当前容量用完((由于插入更多元素而导致的结果)

  1. 创建了具有更大容量的新连续内存块。
  2. 来自旧块的元素被复制
  3. 到这个新块。
  4. 旧内存块被破坏。
  5. 存储在旧存储块中的对象的引用,指针甚至迭代器都无效。
  6. 如果知道向量中要存储的项目总数,则可以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::liststd::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;
}
© www.soinside.com 2019 - 2024. All rights reserved.