IT story

지도에 요소를 삽입하는 권장 방법

hot-time 2020. 9. 5. 10:36
반응형

지도에 요소를 삽입하는 권장 방법


중복 가능성 :
STL 맵에서 []보다 map :: insert를 사용하는 것이 더 낫습니까?

지도에 요소를 삽입 할 때 권장되는 방법이 무엇인지 궁금합니다. 내가해야합니까

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");
}
  1. 멤버 function을 사용 insert하면 더 적은 값의 함수 호출이 관련된다는 것을 알았습니다 . 그렇다면 insert권장되는 방법을 사용 하고 있습니까?
  2. map[key] = valueway가 사용될 때 기본 생성자가 필요한 이유는 무엇 입니까?

나는 그것이 insert존재 키 값 쌍을 덮어 쓰지 않는다는 것을 알고 있지만 map[key] = value그렇습니다. 그러나 둘 중 하나를 선택하려고 할 때 이것이 내가 고려하는 유일한 요소입니까?

어때

  1. 공연
  2. 값의 기본 생성자의 가용성
  3. ???

  1. insert is not a recommended way - it is one of the ways to insert into map. The difference with operator[] is that the insert can tell whether the element is inserted into the map. Also, if your class has no default constructor, you are forced to use insert.
  2. 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

반응형