gpt4 book ai didi

c++ - vector 迭代器不兼容错误

转载 作者:搜寻专家 更新时间:2023-10-31 01:19:44 25 4
gpt4 key购买 nike

我在运行时遇到 vector 迭代器不兼容错误。它发生在代码部分的最后一行,在 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 :

vector<Human> humans;

其中 Human 是一个类,其构造函数如下:

Human(Deck *d, string n) : Player(d), name(n) { printNameCardsAndTotal(); }

(Human是Player的派生类)

因为 iter 是一个字符串 vector 的迭代器,我不明白为什么我在 for 循环内的那一行得到了不兼容的 vector 迭代器。我并不是想直接对人类使用 iter。

错误在这里:

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

关于c++ - vector 迭代器不兼容错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com