set.erase()函数无法正常工作,我是否存在操作错误?
问题:C++中set.erase()未按预期删除元素
我编写了一段C++程序,要求用户输入以字母T开头的身体部位。当用户输入的单词存在于set集合中时,希望将该单词从set中删除,避免用户重复作答,但set.erase()函数并未生效。以下是我的代码:
#include <iostream> #include <set> using namespace std; int main() { string numOne, numTwo, numThree; int pointOne, pointTwo, pointThree, totalPoint; set<string> ansOne = { "TOE", "TONGUE", "TOOTH" }; cout << "Give A Body Part That Starts With The Letter T"; cout << "\n1. "; cin >> numOne; if (ansOne.find(numOne) == ansOne.end()) { ansOne.erase(numOne); cout << "Wrong!"; pointOne = 0 + 0; } else { cout << "Nice, You got a Point!"; pointOne = 1 + 0; } cout << "\n2. "; cin >> numTwo; if (ansOne.find(numTwo) == ansOne.end()) { ansOne.erase(numTwo); cout << "Wrong!"; pointTwo = 0 + pointOne; } else { cout << "Nice, You got a Point!"; pointTwo = 1 + pointOne; } cout << "\n3. "; cin >> numThree; if (ansOne.find(numThree) == ansOne.end()) { ansOne.erase(numThree); cout << "Wrong!"; pointThree = 0 + pointTwo; } else { cout << "Nice, You got a Point!"; pointThree = 1 + pointTwo; } totalPoint = pointOne + pointTwo + pointThree; cout << "\n" << totalPoint; }
错误原因
核心问题是逻辑判断完全搞反了:
ansOne.find(numOne) == ansOne.end()表示元素不在集合中,此时执行erase毫无意义(因为元素本来就不存在,erase不会做任何操作)。- 你想要的逻辑是:当元素存在于集合中时,才删除它并加分;否则提示错误不加分。
修复后的代码
#include <iostream> #include <set> #include <algorithm> using namespace std; int main() { string input; int totalPoint = 0; set<string> ansOne = { "TOE", "TONGUE", "TOOTH" }; cout << "Give A Body Part That Starts With The Letter T\n"; // 循环3次提问,避免重复代码 for (int i = 1; i <= 3; ++i) { cout << i << ". "; cin >> input; // 统一转大写,避免大小写输入问题 transform(input.begin(), input.end(), input.begin(), ::toupper); if (ansOne.find(input) != ansOne.end()) { // 元素存在,删除并加分 ansOne.erase(input); cout << "Nice, You got a Point!\n"; totalPoint++; } else { // 元素不存在,提示错误 cout << "Wrong!\n"; } } cout << "\nTotal Points: " << totalPoint << endl; }
关键修改点
- 反转判断条件:当
find()不返回end()时(元素存在),执行erase()并加分。 - 统一处理输入:用循环替代重复的三段代码,更简洁易维护。
- 大小写兼容:把用户输入转成大写,避免因为输入小写(比如"toe")导致匹配失败。
- 简化分数计算:直接用一个totalPoint变量累加,逻辑更清晰。
内容的提问来源于stack exchange,提问作者John Carlo Nayan
相关产品推荐
相关产品推荐

