흥미가 있어야 할 질문이 있습니다. "앞으로 초기화"을 (를) std::unordered_map
에 작성하고 싶습니다.지도에서 초기화 최적화 : 키 전달
이것들은 세부 사항입니다. std::string
의 해시 맵을 내 꿈에서 의 사용자 정의 클래스 에 전달 된 멤버 변수를 초기화하여std::unordered_map::operator[]
으로 전달합니다.
이것은 작성한 편리한 코드이지만 어디서부터 시작해야할지 모르겠다.
왜 이런 문제가 있습니까? "문자열이 컨테이너에없는 경우 해시를 계산하고 prop
과 같은 작업을 수행 할 것"과 같은 것을 피하고 싶습니다. 이 if
을 피하면 내 공연에 영향을 줄 수 있습니다. 따라서지도가 컨테이너에 새 항목을 추가 할 때 생성자와 해시는 한 번만 실행됩니다. 그것은 좋은 것입니다.
힌트가 있습니까?
감사합니다. & 건배!
#include <iostream>
#include <string>
#include <unordered_map>
class prop
{
public:
prop(std::string s = "") : s_(s), hash_(std::hash<std::string>()(s))
{
// Automagically forwarding the string in the unordered_map...
};
std::string s_;
std::size_t hash_;
int x;
};
int main(int argc, const char * argv[])
{
// Forward the std::string to the prop constructor... but how?
std::unordered_map<std::string, prop> map;
map["ABC"].x = 1;
map["DEF"].x = 2;
map["GHI"].x = 3;
map["GHI"].x = 9; // This should not call the constructor: the hash is there already
std::cout << map["ABC"].x << " : " << map["ABC"].s_ << " : " << map["ABC"].hash_ << std::endl;
std::cout << map["DEF"].x << " : " << map["DEF"].s_ << " : " << map["DEF"].hash_ << std::endl;
std::cout << map["GHI"].x << " : " << map["GHI"].s_ << " : " << map["GHI"].hash_ << std::endl;
std::cout << map["XXX"].x << " : " << map["XXX"].s_ << " : " << map["XXX"].hash_ << std::endl;
return 0;
}
''prop''를'std :: unordered_set'에 적절한'hash'와 평등 연산으로 저장 하는게 어떨까요? –
컨테이너를 변경할 수는 있지만 어떻게하면 좋지 않은'if '를 사용하지 않을 수 있습니까? 단순히 해시가 필요한 평등이 아닙니다. 실제 클래스에서 주어진 문자열로부터 계산 된'K' 해시를 저장합니다. – senseiwa
다른 값을 기반으로하는 요소 조회와 같은 C++ 14의 향후 기능을 살펴보아야합니다. C++ 14의 [std :: unordered_set :: find] (http://en.cppreference.com/w/cpp/container/unordered_set/find)를 참조하십시오. –