C++ 将元素插入地图的推荐方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6952486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:00:45  来源:igfitidea点击:

Recommended way to insert elements into map

c++stlstdmap

提问by Cheok Yan Cheng

Possible Duplicate:
In STL maps, is it better to use map::insert than []?

可能的重复:
在 STL 映射中,使用 map::insert 比使用 [] 更好吗?

I was wondering, when I insert element into map, what is the recommended way. Should I

我想知道,当我将元素插入地图时,推荐的方式是什么。我是不是该

map[key] = value;

or

或者

map.insert(std::pair<key_type, value_type>(key, value));

I did the following quick test:

我做了以下快速测试:

#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. I realize by using member function insert, less value's function call will be involved. So, is using inserta recommended way?
  2. Why default constructor is needed, when map[key] = valueway is being used?
  1. 我通过使用成员函数实现,insert将涉及较少的值的函数调用。那么,使用insert推荐的方式吗?
  2. 为什么需要默认构造函数,何时map[key] = value使用方法?

I know that insertdoesn't overwrite existence key value pair, but map[key] = valuedoes. However, is this the only factor I take into consideration, when try to choose among the both?

我知道这insert不会覆盖存在键值对,但是map[key] = value会覆盖。但是,这是我在尝试在两者中进行选择时考虑的唯一因素吗?

How about

怎么样

  1. Performance
  2. Availability of value's default constructor
  3. ???
  1. 表现
  2. 值的默认构造函数的可用性
  3. ???

采纳答案by B?ови?

  1. insertis not a recommended way - it is one of the ways to insert into map. The difference with operator[]is that the insertcan 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).
  1. insert不是推荐的方法 - 它是插入地图的方法之一。与 的区别operator[]在于insert可以判断元素是否插入到地图中。此外,如果您的类没有默认构造函数,您将被迫使用insert.
  2. operator[]需要默认构造函数,因为映射检查元素是否存在。如果没有,则它使用默认构造函数创建一个并返回一个引用(或对它的 const 引用)。

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.

因为映射容器不允许有重复的键值,所以插入操作检查每个插入的元素是否已经存在另一个具有相同键值的元素,如果存在,则不插入该元素,并且其映射值在任何情况下都不会改变。道路。

回答by James Kanze

Use insertif you want to insert a new element. insertwill not overwrite an existing element, and you can verify that there was no previously exising element:

使用insert,如果要插入一个新元素。 insert不会覆盖现有元素,您可以验证以前不存在元素:

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.

此表单将覆盖任何现有条目。

回答by Luchian Grigore

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 [] operatorwill.

因此,如果键已经存在,则插入不会更改值[] operator

EDIT:

编辑:

This reminds me of another recent question - why use at()instead of the [] operatorto retrieve values from a vector. Apparently at()throws an exception if the index is out of bounds whereas [] operatordoesn'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.

这让我想起了另一个最近的问题 - 为什么使用at()而不是[] operator从向量中检索值。at()如果索引超出范围,则显然会引发异常,而[] operator没有。在这些情况下,最好查看函数的文档,因为它们会为您提供所有详细信息。但总的来说,没有(或至少不应该)两个函数/运算符做完全相同的事情。

My guess is that, internally, insert()will first check for the entry and afterwards itself use the [] operator.

我的猜测是,在内部,insert()将首先检查条目,然后自己使用[] operator.

回答by x13n

map[key] = valueis provided for easier syntax. It is easier to read and write.

map[key] = value提供更简单的语法。它更容易阅读和写作。

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[].

您需要具有默认构造函数的原因map[key]是在赋值之前对其进行评估。如果 key 不存在于 map 中,则会创建一个新的(使用默认构造函数)并从 返回对它的引用operator[]