2016-12-29 3 views
2

문자열의 모든 문자가 고유한지 여부를 결정하는 프로그램을 작성하고 있습니다. 나는 unordered_set을 사용하여 이것을하려고합니다.std :: unordered_set :: find의 결과를 검사하는 코드가 컴파일되지 않습니다.

#include <iostream> 
#include <unordered_set> 
#include <string> 

using namespace std; 

bool uniqueChars(string word) { 

    unordered_set<char> set; 

    for (int i = 0; i < word.length(); i++) { 
     auto character = set.find(word[i]); 

     // if word[i] is found in set then not all chars are unique 
     if (character == word[i]) { 
      return false; 
     } 
     //else add word[i] to set 
     else { 
      set.insert(word[i]); 
     } 
    } 
    return true; 
} 

int main() { 

    string word; 
    getline(cin, word); 

    bool result = uniqueChars(word); 
    return 0; 
} 

그것은 나에게이 오류주고있다 :

|15|error: no match for 'operator==' (operand types are 'std::__detail::_Node_iterator' and 'char')|

을 내가 그 그 문자가 단어 [i]는 비교할 수 없습니다 의미 생각하지만, 잘 모르겠어요 여기 내 코드입니다.

어떻게하면됩니까?

답변

1

주입니다 std::unordered_set::find 반환 반복자가 아닌 요소입니다. 요소와 직접 비교할 수는 없습니다.

이터레이터를 std::unordered_set::end과 비교하여 요소가 발견되었는지 여부를 확인할 수 있습니다. 예 : BTW

auto character = set.find(word[i]); 

// if word[i] is found in set then not all chars are unique 
if (character != set.end()) { 
    return false; 
} 
//else add word[i] to set 
else { 
    set.insert(word[i]); 
} 

: 더 나은 다른 STL 컨테이너의 이름입니다 변수의 이름으로 set를 사용하지.

+0

고마워요! 그것은 작동하지만 set.end()는 무엇을합니까? 그것은 세트를 통해 반복합니까? – CheetahBongos

+0

@CheetahBongos 아니요, [it] (http://en.cppreference.com/w/cpp/container/unordered_set/end)은 컨테이너의 마지막 요소 뒤에 오는 요소에 반복기를 반환하기 만하면됩니다. 자리 표시 자. – songyuanyao

0
*character == word[i] 

(This is the way to access the characters but it is not needed and it should be guided by a check whether it points to the past to the last element)

* 표시 charcater 기본적 이미 삽입 charcater을 참조한다.

if(character != set1.end()) 
    return false; // as we are sure that it is not unique character string 

역 참조해야합니다. 이 경우에는`set :: end`를 가리키는 반복자를 반환하는지 여부를 결정해야합니다.

그건 그렇고 정말로 당신이하려는 일을하는 간단한 방법이 있습니다.

bool uniqueChars(string word) { 

    unordered_set<char> set1; 

    for (int i = 0; i < word.length(); i++) 
     auto character = set1.insert(word[i]); 

    return set1.size()==word.length(); 
} 

는 "설정"C에서 핵심 단어 ++

+0

set :: end set 컨테이너의 past-the-end 요소를 참조하는 반복기를 반환합니다. past-the-end 요소는 집합 컨테이너의 마지막 요소 뒤에 오는 이론적 요소입니다. 어떤 요소도 가리 키지 않으므로 역 참조하면 안됩니다. – coderredoc

+0

왜 downvote? 나는 내가 필요한 모든 것을 언급했다 .. – coderredoc

+0

'uniqueChars'를 자세히 살펴 보자. 아마도'find'는'insert'입니까? 또한, 당신은 "역 참조하지 말아야한다"는 코멘트에 copypasta'd하지만 대답에서 참조 해제했다. – Potatoswatter

1

insert의 반환 값을 활용하십시오. 삽입 도중 복제본이 발견되었는지 여부를 알려줍니다 (이 경우 아무 것도 삽입되지 않습니다).

bool uniqueChars(string word) { 
    unordered_set<char> set; 
    for (char c : word) { 
     if (! set.insert(c).second) { 
      return false; // set didn't insert c because of a duplicate. 
     } 
    } 
    return true; // No duplicates. 
} 

그러나 이것은 효율적이지 않습니다. unordered_set은 힙 기반 해시 테이블이며 그 구현은 상당히 무겁습니다. 가벼운 비트 벡터는 문자를 분류하는 데 적합합니다.

#include <bitset> 

constexpr int char_values = numeric_limits<char>::max() 
          - numeric_limits<char>::min() + 1; 

bool uniqueChars(string word) { 
    bitset<char_values> set; 

    for (char c : word) { 
     int value_index = c - numeric_limits<char>::min(); 

     if (set[ value_index ]) { 
      return false; 
     } else { 
      set[ value_index ] = true; 
     } 
    } 
    return true; // No duplicates. 
}