【问题标题】:Program for splitting whitespace strings won't work拆分空白字符串的程序不起作用
【发布时间】:2019-12-24 19:20:13
【问题描述】:

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

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

【问题讨论】:

  • @ohndoeisabro 在此声明之后 words.push_back(e);引用 e 可能无效。
  • 仅供参考,std::istringstream 为您完成所有这些工作。
  • @nonock 如果您使用特定于版本的c++?? 标签,请在主c++ 标签之外使用它们(以获得更好的问题可见性)。另外,我在这里看不到任何 C++14 特定的内容,不知道您为什么认为该标签更适合。
  • auto& 在 C++14 上。

标签: c++ vector c++14


【解决方案1】:

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

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

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

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

如果你知道一个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::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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多