一个简单的电话簿程序将联系人推回到向量中

a simple phonebook program push back contacts into the vector

我正在用 C++ 编写一个简单的电话簿程序,但没有使用 类。 我有一个添加联系人的功能。我想知道为什么它不起作用!它不会将联系人推回到向量中,如果你能帮助我,我将非常感激。包括我的代码的和平。

    vector<ContactInfo> add(vector<ContactInfo> contacts, ContactInfo ci){
if(!(isRepetativeContact(contacts, ci)))
    contacts.push_back(ci);
return contacts;
}

这里是 "isRepetativeContact" 函数:

    bool isRepetativeContact(const vector<ContactInfo>& contacts, const ContactInfo& ci){
for(int i = 0 ; i < contacts.size() ; i++)
    if((contacts.size() != 0) && (contacts[i] == ci))
        return true;
return false;

}

我为 ContactInfo 结构重载了 == 运算符:

    bool operator==(const ContactInfo& ci) const {
    return (firstName == ci.firstName && lastName == ci.lastName &&
     phoneNumber == ci.phoneNumber && emailAddress == ci.emailAddress &&
     id == ci.id );
}

您似乎正在使用 std::vector 重新创建 std::set。 尝试使用 std::set

std::pair<iterator,bool> insert( const value_type& value );

插入的return值是一对。 bool 表示该值是否已经在集合中; (插入成功)。迭代器指向 std::set 中的元素(如果该值已经在集合中,则指向现有值)

集合中不能有重复项。