2012-12-05 46 views
4

试图为我的向量定义一个查找函数,因为该向量包含多个数据;这是一个结构如何定义查找功能?

我是在一个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

我该怎么把为t他返回类型和值参数?它是

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 
} 
+0

当Table是一个向量时,“Table.ID”是什么意思? “ID”是什么类型? –

回答

5

C++标准库附带a set of find functions

您在寻找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; }); 
+0

啊,我明白了。谢谢您的帮助。但是在myfind的定义/声明中,我在哪里传入update_ID? – simplycoding

+1

@iarcfsil在我使用的例子中,把你需要的值放在那里。我还将示例更改为更接近您的代码。 – pmr

3

明显的方法是使用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绑定参数。

3

你可以使用std::find_if() 找出它是如何工作

2

您可以通过使用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; 

} 
+0

哦,哇,这真的很简单。我最终采用pmr的建议(本质上同样的事情)。你有什么机会可以解释你的不同吗?我不知道他在回应中定义myfind的行中做了什么 – simplycoding