C ++:有条件地将键和值插入std :: map [英] C++: conditionally inserting a key and value into a std::map

查看:135
本文介绍了C ++:有条件地将键和值插入std :: map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

std::map<string, size_t> word_count;
size_t value = word_count.count("a") == 0 ? 1 : 2;
word_count["a"] = value;

那么word_count [a]的最终值为1,如果我改为:

then the final value of word_count["a"] is 1, as I would expect. If instead I do:

std::map<string, size_t> word_count;
word_count["a"] = word_count.count("a") == 0 ? 1 : 2;

那么word_count [a]的最终值为2.为什么?

then the final value of word_count["a"] is 2. Why!?

推荐答案

正式地,可以首先评估任务的任一侧。由实施决定哪个。如果 word_count 不包含a,则会插入一个,并返回其引用的值。如果 word_count 确实包含一个,则只有后一部分发生。尽管首先评估哪个方面的不确定性,您可以按照可能的执行情况:

Officially, either side of the assignment could be evaluated first. It's up to the implementation to decide which. If word_count does not contain an "a", one is inserted, and an lvalue reference to it returned. If word_count does contain one, only the latter part happens. Despite the uncertainty of which side is evaluated first, you can follow possible executions:

operator [] 插入元素,因为它尚未存在。 count()找到它并返回1,因此最终赋值为2。

operator[] inserts the element since it isn't already there. count() finds it and returns 1, so you end up with it being assigned a value of 2.

operator [] 返回现有元素, count code>找到它并返回1,因此最终赋值为2。

operator[] returns the existing element and count() finds it and returns 1, so you end up with it being assigned a value of 2.

count()返回0,右侧。然后,a被插入到地图中,并且赋值为1.

count() returns 0, so you get 1 from the right side. Then, "a" is inserted into the map and assigned a value of 1.

count()返回1,因此从右侧得到2。然后,访问 word_count [a] ,并为其分配了2个。

count() returns 1, so you get 2 from the right side. Then, word_count["a"] is accessed and has 2 assigned to it.

总之,你不能依赖这个来做你想要的,所以最好使用你可以信赖的东西。 mrfontanini提出了一个好的建议,所以我将它编辑一下:

In short, you can't rely on this to do what you want, so it's better to use something that you can rely on. mrfontanini made a good suggestion, so I'll edit it a bit:

word_count["a"]++;
word_count["a"] = std::min(word_count["a"], 2);

第一行确保它被插入并且值至少为1.第二行限制该值

The first line ensures it is inserted and has a value of at least 1. The second limits that value to a maximum 2, in the case that you do this operation repeatedly.

我以此回答为基础关闭两个东西:

I base this answer off of two things:


  1. 当选择一个面进行评估时,整个面必须在另一面可以开始。

  1. When a side is picked to be evaluated, the whole side has to be evaluated before the other side can start.

word_count [a] = 1 的构造具有明确定义的行为

Constructs such as word_count["a"] = 1 exhibit well-defined behaviour, even in the case that an element is inserted and then assigned to.

下面有一些讨论和讨论无论这些是否真实。我已经做了一些更官方的

There is some debate and discussion below about whether these are true or not. I've made it a bit more official now.

这篇关于C ++:有条件地将键和值插入std :: map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆