背景:
实际代码:https://github.com/lmwunder/ElectorateProgram
我正在编写一个基本程序,它将选举信息存储为数据结构作业的一部分。它应该允许用户跟踪候选人和他们收到的选票。用户可以在选举信息列表中添加、编辑或删除候选人,并且可以保存或加载列表本身。用户还可以创建新列表。
数据结构:
候选人代表如下:
class candidate
{
// Data Members
private: std::string fullName;
private: unsigned votes;
// Function Members
/* Constructors and Destructors */
/* Accessors and Mutators */
};
候选者进一步存储在另一个类的 vector 中:
class electorateList
{
private: bool isValid;
private: bool isModified;
private: std::vector<candidate> electorateData;
}
问题:
当用户想要编辑或删除候选者时,我会提示他们输入候选者的名称,该名称是 std::string
。但是,我不完全明白如何仅使用候选人的姓名来搜索候选人的 std::vector
。对我来说最明显的方法是使用内部提供的名称数据实例化临时“匹配”候选对象,并使用它来与所有 std::vector
成员进行比较。
理想情况下,我想要这样的东西:
// 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;
}
最佳答案
只要该类具有数据成员 fullName 的公共(public)访问器,您就可以应用标准算法 std::find_if
。例如
例如
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;
关于c++ - 通过类的成员搜索类的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22082810/