gpt4 book ai didi

c++ - 如何检查 C++ 集中是否存在类对象?

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:33 25 4
gpt4 key购买 nike

我正在尝试编写一段代码,允许用户输入一定数量的名称,然后检查集合中是否存在包含这些名称的任何对象。我想要的是程序获取用户输入的名称,遍历集合并查看名称是否存在于任何对象元素中,然后将名称是否存在打印到命令行。

出于某种原因,即使名称存在于集合中,它也会为集合中的每个元素打印“名称不存在于集合中”。我怎样才能正确检查这个?另外,即使在找到(或未找到)匹配项之前多次检查失败,我如何才能让它仅打印一次“不存在”消息?

到目前为止我的代码是:

#include <iostream>
#include <set>
#include <string>
#include <cassert>

using namespace std;

class Name {
public:
Name();
Name(string n);
bool operator<(Name right)const;
string get_name()const;
private:
string name;
};

Name::Name(){}

Name::Name(string n)
{
name = n;
}

bool Name::operator<(Name right)const
{
bool result = true;
return result;
}

string Name::get_name()const
{
return "Name name is: " + name + "\n";
}

int main(){

set<Name>NamesSet;
NamesSet.insert(Name("Patrick Star"));
NamesSet.insert(Name("Jason"));
NamesSet.insert(Name("Bob Marl"));
NamesSet.insert(Name("Greg"));
set<Name>::iterator pos;


int numjobs;
string cusname;
cout << "Number of names to enter:" << endl;
cin >> numjobs;
cin.ignore();
if (numjobs != 0 || numjobs > 0) {
for (int i = 0; i != numjobs; i++)
{
cout << endl;
cout << "Name " << i+1 << ": " << endl;
getline(cin, cusname);

for (pos = NamesSet.begin(); pos != NamesSet.end(); pos++)
{
if (NamesSet.count((*pos).get_name()))
{
cout << (*pos).get_name() << " exists in set";
break;
}
else
{
cout << "Name does not exist in set";
}
}
}
}

return 0;
}

最佳答案

你的 Name::operator<是不正确的。它返回 true始终,这意味着 set永远相信二Name比较不相等的对象。

相反,通过返回 this->name < right.name 来比较您的姓名字符串,你应该从你的 set 中看到正确的行为.

(顺便说一句,为了效率起见,您的 operator< 应该采用 const Name &)。

关于c++ - 如何检查 C++ 集中是否存在类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25839650/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com