중첩 된 컨테이너 std::map<int, std::map<T, U> >
이 있고 정수형 키가있는 경우 새 하위 맵을 삽입하거나 하위 맵에 추가하여 올바르게 채우려합니다.조건부로 std :: maps의 std :: map에 삽입하는 좀 더 우아한 방법이 있습니까?
int n = ...;
int m = ...;
obj get_some_random_obj(int i, int j); // returns some object
std::map<int, std::map<int, obj> > container; // prepopulated container
// insert some new obj's. Create a new sub map if key i is not found in container,
// append to existing sub map otherwise
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
std::map<int, std::map<int, obj> >::iterator found = container.find(i);
obj newobj = get_some_random_obj(i,j);
std::pair<int, obj> newpair(j, newobj);
if(found != container.end()) {
found->second.insert(newpair);
} else {
std::map<int, obj> newmap;
newmap.insert(newpair);
container.insert(std::make_pair(i, newmap));
}
}
}
두 질문 :
- 이를 작성하는 더 우아한 (? 더 효율적으로) 방법이 있나요 그래서 나는 다음과 같은 예를 들어 같은 것을 함께했다?
- 위의 코드를 더 추상적으로 만들 수 있으므로
std::map<int, std::map<U,T>
유형의 컨테이너를 임의 유형으로U
및T
과 같이 채울 수 있습니까? 나는 템플릿 함수를 만들려고했지만, 전혀 작동하지 못했습니다.
도움 주셔서 감사합니다.
간단 함 ... 고맙습니다. – bbtrb