如何定义查找函数
How do I define a find function?
试图为我的向量定义一个查找函数,因为向量包含多个数据;它是一个结构的向量
我正在输入一个 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 的数据成员
我想做的另一个选择是创建我自己的查找函数,我对如何定义有点困惑
我想返回 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
}
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; });
显而易见的方法是将std::find_if()
与谓词一起使用。使用 2011 C++表示法,这可能如下所示:
std::vector<Employee>::iterator it(std::find_if(Table.begin(), Table.end(),
[=](Employee const& e) { return e.ID == update_ID; });
如果不能使用 C++ 2011,则可以为谓词创建函数对象,也可以使用具有update_ID
绑定参数的合适函数。
你可以使用std::find_if()
了解它是如何工作的
您可以通过使用
find_if 来使用自己的匹配函数。我假设在您的第一个代码段中,您指的是具有成员 ID、ch1、ch2 的员工,而不是表。解决问题的一种方法是:
#include <vector>
#include<iostream>
#include<algorithm>
using std::cout;
using std::endl;
using std::vector;
struct Employee{
int ID;
int ch1;
int ch2;
};
int IDmatch;
bool match_id( Employee myemp){
return myemp.ID==IDmatch;
}
int main(){
vector<Employee> Table;
// fill example vector
Employee temp; // use this for inserting structs into your vector
for(int i=0; i<10; i++){
temp.ID = i; // 1,2,3,...
temp.ch1 = 10*i+1; // 11,21,32,...
temp.ch2 = 10*i+2; // 12,22,32,...
Table.push_back(temp);
}
vector<Employee>::iterator itv;
IDmatch = 3;
itv = find_if(Table.begin(), Table.end(), match_id);
cout << "found an Employee with ID=" << IDmatch << ": ch1=" << itv->ch1 << ", ch2=" << itv->ch2 << endl;
}
相关文章:
- 递归ASMVisitor 和查找函数调用站点
- C++ - 查找函数无法在子字符串上执行
- 查找函数是否为常量
- GDB 如何查找函数退出的位置
- 查找函数在unordered_map中的工作方式是搜索键值
- 在 C++ <algorithm>中查找函数
- 错误:二进制表达式的操作数无效(映射使用查找函数错误)
- 哪个查找规则阻止编译器查找函数
- 在C++中查找函数的调用方(Visual Studio)
- 关于获取行和字符串查找函数的问题
- 查找函数在失败结果中应该返回什么
- 如何使用调用和别名指令在 llvm 字节码中查找函数名称
- std::字符串类查找函数不返回预期结果.我可能用错了
- 在成对向量中查找函数时出错
- 从堆栈指针中查找函数参数值
- 如何定义查找函数
- 如何查找函数是否可重入
- 在c++中查找函数
- GNU g++ 4.9.2 查找函数调用的编译错误
- 使用GDB查找函数对应的内存地址/调试