[英]vector iterators incompatible error
在运行时出现矢量迭代器不兼容错误。 发生错误的行在代码部分的最后,在for循环内(humans.push_back(Human(&deck,(* iter)));)当我第一次遇到错误时,我使用的迭代器不同于错误地使用了“ iter”,因此运行时错误完全有意义。 但是,现在我更改了它并重新编译了所有内容(我再次检查了该内容),仍然收到此错误。
void BlackjackGame::getHumansAndHouse()
{
// asks how many players, pushes_back vector accordingly, initializes house, checking for valid input throughout
string input;
vector<string> names;
while(true)
{
cout << "How many humans? (1 - 7)" << endl;
cin >> input;
if(!isdigit(input[0]))
cout << "Invalid input. ";
else
{
input.erase(1);
int j = atoi(input.c_str());
for(int i = 1; i <= j; i++)
{
while(true)
{
cout << "Enter player " << i << " name: ";
cin >> input;
if(strcmp(input.c_str(), "House") == 0)
cout << "Player name has to be different than 'House'." << endl;
else
{
names.push_back(input);
break;
}
}
}
break;
}
}
vector<string>::iterator iter;
for(iter = names.begin(); iter != names.end(); iter++)
humans.push_back( Human(&deck, (*iter)) );
house = House(&deck);
}
人类是向量:
vector<Human> humans;
其中Human是一个类,其构造函数如下:
Human(Deck *d, string n) : Player(d), name(n) { printNameCardsAndTotal(); }
(人类是玩家的派生类)
由于iter是字符串向量的迭代器,因此我不明白为什么在for循环内的那一行中会得到不兼容的向量迭代器。 并不是我想直接将它用于人类。
错误在这里:
humans.push_back( Human(&deck, (*iter)) );
错误出现在您未显示的代码中。 我根据您的代码和描述编写的以下代码不会产生任何错误:
#include <vector>
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cctype>
using namespace std;
class Deck
{
};
class Player()
{
public:
Player(Deck *d) {}
};
class Human : public Player
{
public:
Human(Deck *d, string n) : Player(d), name(n) {}
private:
string name;
};
class House
{
public:
House(Deck *d) {}
};
int main()
{
Deck deck;
vector<Human> humans;
string input;
vector<string> names;
while(true)
{
cout << "How many humans? (1 - 7)" << endl;
cin >> input;
if(!isdigit(input[0]))
cout << "Invalid input. ";
else
{
input.erase(1);
int j = atoi(input.c_str());
for(int i = 1; i <= j; i++)
{
while(true)
{
cout << "Enter player " << i << " name: ";
cin >> input;
if(strcmp(input.c_str(), "House") == 0)
cout << "Player name has to be different than 'House'." << endl;
else
{
names.push_back(input);
break;
}
}
}
break;
}
}
vector<string>::iterator iter;
for(iter = names.begin(); iter != names.end(); iter++)
humans.push_back( Human(&deck, (*iter)) );
House house = House(&deck);
return 0;
}
相反,尝试
iter != names.end()
始终在for循环中预递增迭代器,并将it != end
用作C ++中的哨兵(这也适用于int
。
for(iter = names.begin(); iter **!=** names.end(); **++iter**)
Microsoft <vector>
标头实现在您的构建中启用了一些调试检查,这些调试检查使迭代器比单纯的指针丰富得多的对象-它们跟踪通过其进行迭代的容器,其“邻居”迭代器以及所要对象指向。 您遇到的断言是检查应该指向同一个容器的2个迭代器,但是发现它们没有指向(根据迭代器的状态)。
因此,您正在破坏某个地方的迭代器对象/列表,或者正在执行未在代码段中显示的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.