我试图为我的向量定义一个find函数,因为这个向量包含多个数据;它是一个结构的向量
我正在输入一个ID,并尝试在我的表中搜索该ID并找到它的索引(如果该ID已经存在)
所以我在这里有声明:
vector<Employee> Table;
vector<Employee>::iterator It;
vector<Employee>::iterator find_It;
//Table has these values
//Table.ID, Table.ch1, Table.ch2
我试着在这里找到ID:
cin >> update_ID;
find_It = find(Table.begin(), Table.end(), update_ID);
有没有办法用变量update_ID进行查找呢?
我试过这样做:
find_It = find(Table.begin(), Table.end(), (*It).update_ID;
但是很明显,我的向量员工没有名为update_ID的数据成员
我正在考虑做的另一个选择是创建我自己的find函数,我对如何定义它有点困惑
我想返回ID的索引,其中Table.ID = update_ID
我应该放什么作为返回类型和值参数?是吗
returntype find( Iterator, Iterator, update ID)
{
for (vector<Employee>::iterator myit = Table.begin(), Table.end(), myit++)
{
if update_ID == Table.ID
{
return myit;
}
}
return myit
}
发布于 2012-12-05 23:43:44
a set of find functions附带了C++标准库。
您正在寻找find_if
,它接受指定比较的函数器。
// a functor taking the update_ID you
// are looking for as an argument in the constructor
struct myfind {
myfind(int needle) : needle(needle) {}
int needle;
bool operator()(const Employee& x) {
return x.ID == needle;
}
};
// use as
int update_ID = 23;
std::find_if(begin(Table), end(Table), myfind(update_ID));
您还可以使用lambda:
int id;
std::find_if(begin(Table), end(Table),
[=](const Employee& x) { return x.update_ID == id; });
发布于 2012-12-05 23:43:43
最明显的方法是将std::find_if()
与谓词一起使用。使用C++ 2011表示法可能如下所示:
std::vector<Employee>::iterator it(std::find_if(Table.begin(), Table.end(),
[=](Employee const& e) { return e.ID == update_ID; });
如果您不能使用C++ 2011,您可以为谓词创建一个函数对象,或者为update_ID
使用一个带有绑定参数的合适函数。
发布于 2012-12-06 00:05:09
您可以使用std::find_if()
了解它是如何工作的
https://stackoverflow.com/questions/13734511
复制相似问题