检查容器是否具有值 (c++)

Checking if Container has Value (c++)

本文关键字:c++ 是否 检查      更新时间:2023-10-16

我有一个自定义类'团队',它的属性之一是它的'名称'。创建每个"团队"后,我将其添加到矢量团队列表中。

我想实现一个函数,不断提示用户输入团队名称,该名称尚未被teamList中的团队采用。我有以下代码:

while (true) {
    string newString;
    bool flag = true;
    getline(cin, newString);
    for (int i = 0; i < teamList.size(); i++) {
        if (teamList[i].name.compare(newString) == 0) flag = false; 
    }
    if (flag == true) {
        return newString;
    } else {
        cout << "name already taken." << endl;
    }
}

但是,这段代码真的很丑;有没有更好的检查方法?另外,一个更普遍的问题 - 面对丑陋的代码问题(像这个),我可以采取什么样的步骤来找到一个新的,更干净的实现?谢谢。

我会使用 std::set ,它为您处理重复项。例如,您可以看到该类是按字符串成员排序的,当在 main 中插入三个时,只有两个保留,因为其中两个插入具有相同的字符串,因此它们被视为平等。

#include <iostream>
#include <set>
#include <string>
struct SetThing {
    SetThing(int value, const std::string &value2) : i(value), s(value2){}
    int i;
    std::string s;
    bool operator<(const SetThing &other) const {
        return s < other.s;
    }
};
int main() {
    std::set<SetThing> s;
    s.insert(SetThing(5, "abc"));
    s.insert(SetThing(4, "def"));
    s.insert(SetThing(6, "abc"));
    std::cout << s.size();
}

现在要插入,您可以在返回对的second成员false时重新提示:

do {
    //get input
} while (!teamList.insert(somethingBasedOnInput).second);

team中定义一个相等运算符,可以将team与字符串进行比较:

  bool team::operator==(string s) const
  {
    return(s==name);
  }

然后你可以使用find

vector<team>::const_iterator itr = find(teamList.begin(), teamList.end(),
                                        newString);
if(itr!=league.end())
  cout << "name already taken" << endl;