Search code examples
c++vectorpush-back

a simple phonebook program push back contacts into the vector


I'm writing a simple phonebook program in c++ not using classes. I have a function which add a contact. I wonder why it doesn't work! it doesn't push back the contact into the vector I would be very thankful if you could help me. A peace of my code is included.

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

and here is the "isRepetativeContact" function:

    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;

}

And I overloaded the == operator for ContactInfo struct:

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

Solution

  • Seems like you are recreating an std::set using std::vector. Try using an std::set

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

    the return value of insert is a pair. The bool indicates whether the value was already in the set or not; (insertion succeeded). The iterator points to the element in the std::set (if the value was already in the set, it points to the existing value)

    You cannot have duplicates in a set.