试图为我的向量定义一个查找函数,因为该向量包含多个数据; 它是结构的向量
我正在输入一个ID,我正在尝试在我的表中搜索它并查找其索引(如果该ID已存在)
所以我在这里有声明:
vector<Employee> Table;
vector<Employee>::iterator It;
vector<Employee>::iterator find_It;
//Table has these values
//Table.ID, Table.ch1, Table.ch2
Run Code Online (Sandbox Code Playgroud)
而我正试图在这里找到ID:
cin >> update_ID;
find_It = find(Table.begin(), Table.end(), update_ID);
Run Code Online (Sandbox Code Playgroud)
是否有办法使用变量update_ID进行查找?
我试过这样做:
find_It = find(Table.begin(), Table.end(), (*It).update_ID;
Run Code Online (Sandbox Code Playgroud)
但显然我的矢量Employee没有名为update_ID的数据成员
我想要做的另一个选择是创建我自己的find函数,我对如何定义有点困惑
我想返回Table.ID = update_ID的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
}
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
你也可以使用lambda:
int id;
std::find_if(begin(Table), end(Table),
[=](const Employee& x) { return x.update_ID == id; });
Run Code Online (Sandbox Code Playgroud)