简体   繁体   中英

Search a Vector of Classes by a member of the Class

Background:

Actual Code: https://github.com/lmwunder/ElectorateProgram

I'm writing a basic program that stores election information as part of an assignment for Data Structures. It is supposed to allow users to track candidates and the votes that they've received. Users can add, edit, or remove candidates from the election information list, and the list itself can be saved or loaded. Users can also create new lists.

Data Structures:

Candidates are represented as follows:

class candidate
{
    // Data Members
    private: std::string fullName;
    private: unsigned votes;
    // Function Members
    /* Constructors and Destructors */
    /* Accessors and Mutators */
};

Candidates are further stored in a vector of another class:

class electorateList
{
    private: bool isValid;
    private: bool isModified;
    private: std::vector<candidate> electorateData;
}

Question:

When the users wants to edit or remove a candidate, I prompt them for the name of the candidate, which is a std::string . However, I don't exactly see how I can search the std::vector of candidates using only the name of the candidate. The most obvious way for me is to instantiate temporary "match" candidate object with the name data provided inside, and use that to compare against all std::vector members.

Ideally, I'm going for something like this:

// Find a candidate by name and return their position in the vector
std::vector<candidate>::iterator electorateList::find( std::string &name )
{
    std::vector<candidate>::iterator position = electorateData.end();
    // Binary search over all the vector elements
    // If candidate is matched ( found ), set the iterator to the position in the vector the match is
    /* position = // electorateData.at( whereEver );
    // Else, return the end iterator of the array
    return position;
}

You can apply standard algorithm std::find_if provided that the class has public accessor to data member fullName. For example

For example

auto it = std::find_if( electorateData.begin(), electorateData.end(),
                        [&]( const candidate &c ) { return ( c.fullNameAccessor() == name ); } );

if ( it != electorateData.end() ) std::cout << "There is such candidate." << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM