자료구조 & 알고리즘/기타

unordered_map은 역순회가 불가능하다.

diesuki4 2023. 4. 5. 19:59

 

 

How to get the last element of an std::unordered_map?

How to get the last element of an std::unordered_map? myMap.rbegin() and --myMap.end() are not possible.

stackoverflow.com

unordered_map은 역순회가 불가능하므로, 다음과 같이 사용할 수 없다.

  • 특이하게도 MSVC에서는 되는데, GCC에서는 작동하지 않는다.

 

void func()
{
    unordered_map<string, int> umap {{"A", 1}, {"B", 2}, {"C", 3}};
    
    // 런타임 오류 발생 ! !
    auto it = prev(umap.end());
    it = umap.end() - 1;
}

 

그러므로 해시 테이블을 사용하는데 마지막 원소를 가져와야하는 경우라면, 어쩔 수 없이 map을 사용해야 한다.

 

void func()
{
    map<string, int> mp {{"A", 1}, {"B", 2}, {"C", 3}};
    
    auto it = mp.rbegin();
}