【问题标题】:Checking if Container has Value (c++)检查容器是否有值(c++)
【发布时间】:2012-11-06 09:20:59
【问题描述】:

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

我想实现一个功能,该功能会不断提示用户输入尚未被 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;
    }
}

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

【问题讨论】:

  • 查看find
  • set(以及扩展,find)的问题在于它包含我正在使用的所有通用“结构”——而不是名称列表。因此,我需要找到一种方法将用户的字符串与每个 player.name 进行比较
  • @MichaelHang 这听起来没什么问题。你关心容器内物品的顺序吗?

标签: c++ contain


【解决方案1】:

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;

【讨论】:

    【解决方案2】:

    我会使用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);
    

    【讨论】:

    • 如果我将矢量 换成 set,我将如何确保尚未使用新字符串?我已经考虑过集合的 .find 函数,但这会将字符串与“团队”对象进行比较,而不是 team.name 字段...
    • @MichaelHang,它根据您的operator&lt; 进行比较。正如您在我的回答中看到的,尽管有三个不同的整数,size() 返回 2,因为有两个唯一的字符串,operator&lt; 只比较字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多