2012-12-05 4 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의 인덱스를 반환 할

을 정의하는 방법에 약간 혼란 스러워요 어디 t로두고 무엇을 Table.ID = update_ID

그는 유형 및 값 매개 변수를 반환합니까? 그것입니까

+0

Table이 벡터 일 때의 의미는 무엇입니까? '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)); 

또한 람다를 사용할 수 있습니다

int id; 
std::find_if(begin(Table), end(Table), 
      [=](const Employee& x) { return x.update_ID == id; }); 
+0

아하이 봐요. 도와 주셔서 감사합니다. 그러나 myfind 정의/선언에서 update_ID는 어디에서 전달합니까? – simplycoding

+1

@iarcfsil 예제에서 23을 사용했습니다. 필요한 값을 입력하십시오. 또한 예제를 코드에 가깝게 변경했습니다. – pmr

3

확실한 접근 방식은 술어와 함께 std::find_if()을 사용하는 것입니다. 이과 같이 볼 수 있었다 C++ 2011 표기법을 사용 : 당신이 C++ 2011을 사용할 수없는 경우, 당신은 술어 함수 객체를 만들거나 update_ID에 대한 바운드 인수와 함께 적절한 기능을 사용할 수 있습니다

std::vector<Employee>::iterator it(std::find_if(Table.begin(), Table.end(), 
            [=](Employee const& e) { return e.ID == update_ID; }); 

.

3

당신은 당신은 find_if을 사용하여 자신 만의 매칭 기능을 사용할 수 있습니다

2

를 작동하는 방법 std::find_if() 알아 사용할 수 있습니다. 첫 번째 코드 단편에서 테이블이 아닌 구성원 ID, ch1, ch2를 갖는 Employee를 가리키는 것으로 가정합니다. 문제를 해결할 수있는 한 가지 방법은 다음과 같습니다.

#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

관련 문제