![](/img/trans.png)
[英]Initialize a vector of classes that have member pointers to another class' member variables
[英]Search a Vector of Classes by a member of the Class
背景:
实际代码: https : //github.com/lmwunder/ElectorateProgram
我正在编写一个基本程序,该程序将选举信息存储为数据结构分配的一部分。 它应该允许用户跟踪候选人和他们收到的选票。 用户可以从选举信息列表中添加,编辑或删除候选者,并且列表本身可以保存或加载。 用户还可以创建新列表。
数据结构:
候选人代表如下:
class candidate
{
// Data Members
private: std::string fullName;
private: unsigned votes;
// Function Members
/* Constructors and Destructors */
/* Accessors and Mutators */
};
候选者进一步存储在另一个类的向量中:
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;
}
您可以应用标准算法std::find_if
前提是该类具有对数据成员fullName的公共访问器。 例如
例如
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.