从列表中删除元素时出现问题

Trouble removing elements from list

本文关键字:问题 元素 列表 删除      更新时间:2023-10-16

我有一个成对字符串的列表,然后我删除每个列表的顶部元素并进行比较。但是,当我删除列表大小的顶部元素时,列表大小会大大增加。我已经尝试了pop_front(),制作了迭代器等,我知道如何发生同样的问题。

std::ifstream myReadFile;
std::list<std::pair<std::string,std::string>> startTape;
std::pair<std::string,std::string> pair;
while (std::getline(myReadFile, pair.first , ','))
{
    std::getline(myReadFile, pair.second);
    startTape.push_back(pair);
}
myReadFile.close();

启动磁带 { 大小=8 }

std::pair<std::string,std::string> firstCompare = startTape.front();
startTape.remove(*startTape.begin());
std::pair<std::string,std::string> secondCompare = startTape.front();
startTape.remove(*startTape.begin());

startTape { size=1753706592 }

当我查看 startTape 列表时,它似乎已经循环了。

(读取文件内容如下)N,C/nI,G/nA,U/nH,A/n克,米/nC,I/nS,H/nU,N/n

我写了一个完整的程序,其中包括你上面提到的所有内容我确实稍微改变了文件的读取方式 - 我不熟悉你调用 getline() 的方式,其中第一个参数是流名称,所以我创建了一个字符缓冲区来读取各个元素,然后将它们复制到对。我还确保我不会在文件末尾做一些疯狂的事情,以防没有读取两个元素(无论文件末尾是否有 都可以)。

#include <fstream>
#include <iostream>
#include <list>
#define BUF 100
using namespace std;
int main() {
  std::ifstream myReadFile;
  std::list<std::pair<std::string,std::string> > startTape;
  std::pair<std::string,std::string> pair;
  char sbuf[BUF]; // temp storage for file read
  myReadFile.open("listOwords.txt");
  if(!myReadFile) {
    cerr << "Error: file could not be opened" << endl;
    exit(1);
  }
  cout << "file opened successfully" << endl;
  while(myReadFile.getline(sbuf, BUF, ',')) {
    pair.first = sbuf;
    myReadFile.getline(sbuf, BUF);
    pair.second = sbuf;
    if(myReadFile.good()) {
      // only process if both elements were read successfully
      // this deals with the problem of a "half pair" being read if the file is terminated with n
      startTape.push_back(pair);
      cout << "read a pair: " << pair.first << ", " << pair.second << endl;
      }
  }  
  myReadFile.close();
  cout << "Size of startTape is now " << startTape.size() << endl;
  std::pair<std::string,std::string> firstCompare = startTape.front();
  startTape.remove(*startTape.begin());
  cout << "Size of startTape is now " << startTape.size() << endl;
  std::pair<std::string,std::string> secondCompare = startTape.front();
  startTape.remove(*startTape.begin());
  cout << "Size of startTape is now " << startTape.size() << endl;
  exit(0);
}

列表Owords的内容:

>cat listOwords.txt 
N, C
I, G
A, U
H, A
G, M
C, I
S, H
U, N

我从中得到的输出是:

file opened successfully
read a pair: N,  C
read a pair: I,  G
read a pair: A,  U
read a pair: H,  A
read a pair: G,  M
read a pair: C,  I
read a pair: S,  H
read a pair: U,  N
Size of startTape is now 8
Size of startTape is now 7
Size of startTape is now 6

让我知道您是否使用此确切代码没有得到相同的结果?

我认为您考虑的列表方向是错误的。列表的"顶部"是"返回"(push_back,pop_back)或"结束"(rbegin)。

尝试使用 back() 而不是 front(),并使用 pop_front() 来删除第一个元素。

尽管如此,像这样变化的列表大小听起来更像是某个地方的错误。