C++ 从列表中删除元素时遇到问题
我有一个成对字符串的列表,然后删除每个列表的顶部元素并比较它们。 但是,当我删除列表大小大大增加的顶部元素时。 我尝试过pop_front(),制作了迭代器等。我知道同样的问题是如何发生的C++ 从列表中删除元素时遇到问题,c++,list,C++,List,我有一个成对字符串的列表,然后删除每个列表的顶部元素并比较它们。 但是,当我删除列表大小大大增加的顶部元素时。 我尝试过pop_front(),制作了迭代器等。我知道同样的问题是如何发生的 std::ifstream myReadFile; std::list<std::pair<std::string,std::string>> startTape; std::pair<std::string,std::string> pair; while (std::
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();
std::ifstream myReadFile;
std::列表startTape;
std::成对;
while(std::getline(myReadFile,pair.first,','))
{
std::getline(myReadFile,pair.second);
开始时,向后推(成对);
}
myReadFile.close();
startTape{size=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());
std::pair firstCompare=startTape.front();
startTape.remove(*startTape.begin());
std::pair secondCompare=startTape.front();
startTape.remove(*startTape.begin());
startTape{size=1753706592}
当我查看startTape列表时,它似乎出现了循环
(readFile内容如下)
N、 C/N
一、 总干事
A、 联合国
H、 A/n
G、 M/n
C、 识别号
S、 H/n
U、 N/N我认为你认为列表方向错了。列表中的“顶部”是“后退”(向后推,向后弹出)或“结束”(rbegin) 尝试使用back()而不是front(),并使用pop_front()删除第一个元素
尽管如此,列表大小的变化听起来更像是某个地方的一个bug。我编写了一个完整的程序,其中包含了上面提到的所有内容 我确实稍微改变了文件的读取方式——我不熟悉调用getline()的方式,其中第一个参数是流名称,所以我创建了一个字符缓冲区来读取各个元素,然后将它们复制到对中。我还确保在文件末尾不会做一些疯狂的事情,以防没有读取两个元素(无论文件末尾是否有一个\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
如果您无法使用此代码获得相同的结果,请告诉我?从您正在查看的列表前面删除内容通常是个坏主意。。。奇怪的事情会发生。您试图用代码实现什么?这是合并排序的第一阶段。我将前端复制到两对变量,然后比较它们,看哪个更大。然后将它们放入一个新的列表中。你能显示重现问题的最小代码吗?列表中的所有元素都与第一个元素具有相同的值吗?如果是这样的话,这将清除列表,导致在一个未定义的空列表上调用front。您的错误一定在其他地方。第一个比较的值N、C和第二个比较的值是I、G,这些都是正确的,但是循环的大小会被破坏,我以后的循环取决于大小。我得到的结果与您完全相同,我不确定为什么错误会出现在我的其他代码上。但这是一个很好的方法。谢谢,很高兴它对你有用。不客气。
>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