我正在用 C++ 制作 D&D 游戏。我随机滚动 6 个分数,将它们放在一个 vector 中,将它们显示给玩家。然后我遍历每个能力(str、dex、con、int、wis 和 cha),并调用一个函数询问玩家他们想为每个能力使用哪个分数,然后我将其从 vector 中删除,返回值,然后继续下一个能力。除非有重复的卷,否则它工作正常,在这种情况下,它会删除两个重复项。我希望它一次只删除一个而不考虑重复项,而且我无法在网上找到任何东西来执行此操作。这是函数调用
int Character::initScores(std::vector<int> & v, std::string ability)
{
int c = 0;
bool error = 0;
do {
if (c != 0) {
std::cout << "That isn't one of your scores. Try again. " <<
std::endl;
}
int choice;
std::cout << ability << ": ";
std::cin >> choice;
if (std::find(v.begin(), v.end(), choice) != v.end())
{
v.erase(std::remove(v.begin(), v.end(), choice), v.end());
std::cout << "Your remaining rolls are ";
for (int i = 0; i < v.size(); i++)
std::cout << v[i] << " ";
std::cout << std::endl;
return choice;
}
else
{
c++;
error = 1;
}
} while (error = 1);
}
函数调用
std::cout << "Enter which score you want for... " << std::endl;
strength = initScores(scores, "Strength");
dexterity = initScores(scores, "Dexterity");
constitution = initScores(scores, "Constitution");
intelligence = initScores(scores, "Intelligence");
wisdom = initScores(scores, "Wisdom");
charisma = initScores(scores, "Charisma");
如果我的代码中有任何低效/错误的做法,也请 lmk,我最近才开始从事自己的编码项目
最佳答案
您正在调用 std::remove()
,它从容器中“移除”所有匹配值(实际上,它只是将它们移动到容器的末尾),然后您正在调用erase()
方法的 2 参数重载,用于从容器中物理删除所有“已删除”值。
如果您只想删除 1 个元素,请将 std::find()
返回的迭代器传递给 erase()
方法的 1 参数重载:
auto iter = std::find(v.begin(), v.end(), choice);
if (iter != v.end())
{
v.erase(iter);
...
}
关于c++ - 如何从具有重复项的 vector 中仅删除一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868098/