gpt4 book ai didi

c++ - 在 C++ 中实现计数器时映射构造函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:44 25 4
gpt4 key购买 nike

我现在正在用 C++ 尝试 STL,发现一个我不明白的问题。我想象一个问题需要显示每个元素以及它在 vector 中出现的次数。由于我知道如何使用 vector 来完成这个问题,所以我尝试使用“set”或“map”来解决这个问题。

vector<char> v{ 'a', 'b', 'f', 'b', 'd', 'c', 'b', 'f', 's', 'v', 'x'};
map<char, int> m; // <key, counter>
for (char n : v)
m.insert(pair<char, int>(n, m[n]+1));

我认为每次找到 key 时它都会使计数器加,但是,计数器不起作用并且每个计数器都是 0。一些变化后:

vector<char> v{ 'a', 'b', 'f', 'b', 'd', 'c', 'b', 'f', 's', 'v', 'x'};
map<char, int> m; // <key, counter>
for (char n : v)
m.insert(pair<char, int>(n, m[n]++));

然后就可以了。我不知道为什么。

最佳答案

首先,您尝试通过调用 insert 更新 map 条目的尝试都会被忽略,因为如果条目已存在,insert 不会执行任何操作。引用自C++ reference :

Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.

如果您稍微重写一下代码,它会变得更清晰一些:

for (char n : v)
{
int& count = m[n];
int new_count = count + 1;
pair<char, int> p(n, new_count);
m.insert(p); // ignored because the key already exists
}

不过,第二个版本直接修改了 map 内部的计数,因为 operator[] 返回了一个对存储值的 reference,而 operator++ 直接操作int。您重写的第二个版本看起来像这样:

for (char n : v)
{
int& count = m[n];
count++; // operates on the value that is stored in the map
pair<char, int> p(n, count);
m.insert(p); // ignored because the key already exists
}

即使您尝试将新对插入 map 的尝试再次被忽略,因为您直接修改了存储在 map 中的值,第二个版本会执行您希望您的代码首先执行的操作。

关于c++ - 在 C++ 中实现计数器时映射构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com