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

发布于 2024-11-27 19:39:34 字数 1781 浏览 6 评论 0原文

可能的重复:
在STL地图中,使用map::更好插入比[]?

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

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. 我意识到通过使用成员函数insert,将涉及较少的值的函数调用。那么,使用 insert 是推荐的方法吗?
  2. 当使用map[key] = value方式时,为什么需要默认构造函数?

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

怎么样

  1. 性能
  2. 值的默认构造函数的可用性
  3. ???

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

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 insert a recommended way?
  2. Why default constructor is needed, when map[key] = value way is being used?

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

How about

  1. Performance
  2. Availability of value's default constructor
  3. ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

阪姬 2024-12-04 19:39:34
  1. insert 不是推荐的方法 - 它是插入地图的方法之一。与operator[]的区别在于insert可以判断元素是否插入到map中。另外,如果您的类没有默认构造函数,则您必须使用 insert
  2. operator[] 需要默认构造函数,因为映射会检查元素是否存在。如果没有,那么它会使用默认构造函数创建一个并返回一个引用(或对其的 const 引用)。

由于映射容器不允许重复的键值,因此插入操作会检查插入的每个元素是否已存在于容器中具有相同键值的另一个元素,如果存在,则不会插入该元素,并且不会更改其映射值。方式。

  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.

没有伤那来痛 2024-12-04 19:39:34

如果要插入新元素,请使用 insert插入不会
覆盖现有元素,您可以验证是否没有
先前存在的元素:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

如果要覆盖可能存在的元素,请使用 []

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

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

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.

随心而道 2024-12-04 19:39:34

引用:

由于映射容器不允许重复的键值,因此插入操作会检查插入的每个元素是否已存在于容器中具有相同键值的另一个元素,如果存在,则不会插入该元素,并且不会插入其映射值以任何方式改变。

因此,如果键已经存在,则 insert 不会更改值,而 [] 运算符 会。

编辑:

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

我的猜测是,在内部,insert() 将首先检查条目,然后使用 [] 运算符

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.

万劫不复 2024-12-04 19:39:34

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

您需要默认构造函数的原因是 map[key] 在赋值之前进行评估。如果映射中不存在键,则会创建新的键(使用默认构造函数),并从 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[].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文