检查容器是否具有值 (c++)
Checking if Container has Value (c++)
我有一个自定义类'团队',它的属性之一是它的'名称'。创建每个"团队"后,我将其添加到矢量团队列表中。
我想实现一个函数,不断提示用户输入团队名称,该名称尚未被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;
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 检查输入是否不是整数或数字
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 此代码是否违反一个定义规则
- 是否需要删除包含对象的"pair"?
- 是否可以从int转换为enum类类型
- 无论条件是否为true,if总是在c++中执行
- 如何找到大小'x'数组是否完全填充,在C++?
- 检查值是否在集合p1和p2中,但不在p3中
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- GL_SHADERSTORAGE_BUFFER位置是否与其他着色器位置冲突
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- C/C++预处理器是否可以检测一些编译器选项
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话