2011-05-03 3 views
7

여러 문자열을 포함하는 구조체를 보유하기 위해 집합을 사용하고 있습니다. 세트의 find() 기능을 사용할 수 있기를 원합니다. 그러나 세트가 구조체를 보유하고 있기 때문에 작동하지 않습니다. find()에서 구조체의 문자열 중 하나를 찾았 으면합니다. 어떻게 할 수 있습니까?구조체 집합을 사용하여 찾기 작업 만들기

다음은 사용하려고 시도한 코드입니다. 그것은 find()가 사용되는 부분을 제외하고는 잘 동작합니다.

test.cpp:30:7: error: no matching member function for call to 'find' 
    s.find("key"); 
    ~~^~~~ 
In file included from test.cpp:3: 
In file included from /usr/include/c++/4.2.1/set:65: 
/usr/include/c++/4.2.1/bits/stl_set.h:429:7: note: candidate function not viable: no known conversion from 'const char [4]' to 'const key_type' (aka 'const test') for 1st argument 
     find(const key_type& __x) 
    ^
/usr/include/c++/4.2.1/bits/stl_set.h:433:7: note: candidate function not viable: no known conversion from 'const char [4]' to 'const key_type' (aka 'const test') for 1st argument 
     find(const key_type& __x) const 
    ^
1 error generated. 

답변

0

이 링크를 참조하십시오 : find_if using vectorlist

이 링크는 벡터 또는 템플릿 목록에서 요소를 찾기 위해 사용할 내가 컴파일 할 때

#include <iostream> 
#include <string> 
#include <set> 
using namespace std; 

struct test 
{ 
    string key; 
    string data; 
}; 

bool operator<(const test & l, const test & r) 
{ 
    return l.key < r.key; 
} 

bool operator==(const test & l, const test & r) 
{ 
    return l.key == r.key; 
} 

set<test> s; 

int main() 
{ 
    test newmember; 
    newmember.key = "key"; 
    newmember.data = "data"; 
    s.insert(newmember); 
    s.find("key"); 
} 

다음은 오류 메시지입니다.

2

구조체를 set에 넣으려면 구조체에 operator<을 지정해야합니다. 해당 문자열 구성원을 비교하여 operator< 결과를 반환 할 수 있습니다.

find을 사용하려면 해당 문자열 멤버가 동일하면 true을 반환하도록 구조체에 operator==을 지정할 수 있습니다.

샘플 :

// code from your question used here 

    int main() 

{ 
    test newmember; 
    newmember.key = "key"; 
    newmember.data = "data"; 

    test findMember; 
    findMember.key = "key"; 
    // as operator== and operator< doesn't care about data field we can left it be 
    // initialized by default constructor 

    s.insert(newmember); 
    s.find(findMember); 
} 

당신은 다음과 같은 예를 들어 당신의 test 구조체에 대한 string에서 암시 적 생성자를 제공 할 수 string 매개 변수 find()를 호출 할 경우

struct test { 
//... 
    test(const string &in_key) : key(in_key) {} 
//... 
}; 

을하지만, 암시의 사용 생성자는 코드에서 더 이상 예측할 수없는 변환을 유도 할 수 있기 때문에 좋은 기술이 아닙니다.

+0

그 코드는 무엇입니까? 나는 <연산자를 오버로드 할 수 있지만 같은 메소드는 ==에 대해 작동하지 않습니다. –

+0

@ z-buffer : 내 대답의 업데이트 버전을 참조하십시오. 문제는,'find()'에'test' 구조체의 인스턴스를 제공해야한다는 것입니다. – beduin

11

글로벌 연산자를 오버로드하는 대신 구조체에 operator<operator==를 제안합니다. 훨씬 더 명확합니다. 예를 들면 : 당신의 진짜 문제에 대한 지금에

struct test 
{ 
    string key; 
    string data; 

    bool operator<(const test& rhs) const 
    { 
    return key < rhs.key; 
    } 

    bool operator==(const test& rhs) const 
    { 
    return key == rhs.key; 
    } 
}; 

은 - 당신은 find() 함수에 문자열을 전달하고 있지만 그것은 단지 형 test의 구조체를 사용할 수 있습니다. 이를 위해, 자동 변환에 대한 생성자를 추가, 그래서 최종 구조체는 다음과 같이 보일 것이다 :

struct test 
{  
    string key; 
    string data; 

    test(const std::string& strKey = "", const std::string& strData = "") 
    : key(strKey), 
    data(strData) {} 

    bool operator<(const test& rhs) const 
    { 
    return key < rhs.key; 
    } 

    bool operator==(const test& rhs) const 
    { 
    return key == rhs.key; 
    } 
}; 

자동으로 생성자를 호출하고 만 관련이있는 임시 test 구조체를 만들 것 find()에 문자열을 전달 키. 이 특별한 경우 생성자는 explicit으로 선언되어서는 안됩니다.