지도에 요소를 삽입하는 권장 방법
지도에 요소를 삽입 할 때 권장되는 방법이 무엇인지 궁금합니다. 내가해야합니까
map[key] = value;
또는
map.insert(std::pair<key_type, value_type>(key, value));
다음과 같은 빠른 테스트를 수행했습니다.
#include <map>
#include <string>
#include <iostream>
class Food {
public:
Food(const std::string& name) : name(name) { std::cout << "constructor with string parameter" << std::endl; }
Food(const Food& f) : name(f.name) { std::cout << "copy" << std::endl; }
Food& operator=(const Food& f) { name = f.name; std::cout << "=" << std::endl; return *this; }
Food() { std::cout << "default" << std::endl; }
std::string name;
};
int main() {
std::map<std::string, Food> m0;
/*
1) constructor with string parameter
2) copy
3) copy
4) copy
*/
m0.insert(std::pair<std::string, Food>("Key", Food("Ice Cream")));
/*
1) constructor with string parameter
2) default
3) copy
4) copy
5) =
*/
// If we do not provide default constructor.
// C2512: 'Food::Food' : no appropriate default constructor available
m0["Key"] = Food("Ice Cream");
}
- 멤버 function을 사용
insert
하면 더 적은 값의 함수 호출이 관련된다는 것을 알았습니다 . 그렇다면insert
권장되는 방법을 사용 하고 있습니까? map[key] = value
way가 사용될 때 기본 생성자가 필요한 이유는 무엇 입니까?
나는 그것이 insert
존재 키 값 쌍을 덮어 쓰지 않는다는 것을 알고 있지만 map[key] = value
그렇습니다. 그러나 둘 중 하나를 선택하려고 할 때 이것이 내가 고려하는 유일한 요소입니까?
어때
- 공연
- 값의 기본 생성자의 가용성
- ???
insert
is not a recommended way - it is one of the ways to insert into map. The difference withoperator[]
is that theinsert
can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to useinsert
.operator[]
needs the default constructor because the map checks if the element exists. If it doesn't then it creates one using default constructor and returns a reference (or const reference to it).
Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.
Use insert
if you want to insert a new element. insert
will not overwrite an existing element, and you can verify that there was no previously exising element:
if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
// Element already present...
}
Use []
if you want to overwrite a possibly existing element:
myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition
This form will overwrite any existing entry.
To quote:
Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.
So insert will not change the value if the key already exists, the [] operator
will.
EDIT:
This reminds me of another recent question - why use at()
instead of the [] operator
to retrieve values from a vector. Apparently at()
throws an exception if the index is out of bounds whereas [] operator
doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.
My guess is that, internally, insert()
will first check for the entry and afterwards itself use the [] operator
.
map[key] = value
is provided for easier syntax. It is easier to read and write.
The reason for which you need to have default constructor is that map[key]
is evaluated before assignment. If key wasn't present in map, new one is created (with default constructor) and reference to it is returned from operator[]
.
참고URL : https://stackoverflow.com/questions/6952486/recommended-way-to-insert-elements-into-map
'IT story' 카테고리의 다른 글
RecyclerView에서 특정 항목을 업데이트 / 새로 고침하는 방법 (0) | 2020.09.05 |
---|---|
PHP의 count () 함수는 배열에 대해 O (1) 또는 O (n)입니까? (0) | 2020.09.05 |
크롬 브라우저에서 로케일을 변경하는 방법 (0) | 2020.09.05 |
좋은 C # 예제로 Liskov Substitution Principle을 설명 할 수 있습니까? (0) | 2020.09.05 |
ASP.NET 4.5 프로젝트를 위해 Visual Studio 2015에서 Grunt, Bower, Gulp, NPM 사용 (0) | 2020.09.05 |