C++ 映射将所有键的值显示为 0

标签 c++ c++14

我在 map 中插入一个 vector 中的数字,键为数字,值为原样(索引 + 1)。 但是当我打印 map 的内容时,显示的值是 0,尽管我传递了整数 i。

// taking input of n integers in vector s;
vector<int> s;
for(int i=0;i<n;i++){
    int tmp;cin>>tmp;
    s.push_back(tmp);
}
//creating map int to int
map<int,int> m;
bool done = false;
for(int i=1;i<=s.size();i++){
   //check if number already in map
   if (m[s[i-1]]!=0){
       if (i-m[s[i-1]]>1){
          done = true;
          break;
       }
    }
    // if number was not in map then insert the number and it's index + 1
    else{
          m.insert({s[i-1],i});
    }
}
for(auto it=m.begin();it!=m.end();it++){
    cout<<endl<<it->first<<": "<<it->second<<endl;
}

用于输入 n = 3 和数字作为 1 2 1 in vector s,我希望输出是

1: 1
2: 2

但是输出是

1: 0
2: 0

为什么是 0?怎么了?

最佳答案

评论后的代码块:

// check if number already in map

在逻辑上是错误的,因为 operator[] 实际上会插入一个元素,使用值初始化(a),如果它当前没有存在。

如果您改为使用:

if (m.find(s[i-1]) != m.end())

这样就可以解决这个问题。


(a) 我相信(b) 的值初始化涉及其中一个构造函数;对于数组,数组中的每个项目的值初始化;并且,对于其他类型(这种情况),零初始化。这意味着使用您的方法为您的 key 创建一个零值条目,并返回该零值

然后它将移动到 else block (因为值为零)并尝试执行插入。然而,来自标准(C++20,[map.modifiers] discussing insert)的这个片段意味着没有任何反应:

If the map already contains an element whose key is equivalent to k, there is no effect.


(b) 虽然,正如我的 child 经常指出的那样,并且没有太多提示,我以前也错了 :-)

关于C++ 映射将所有键的值显示为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61632099/

相关文章:

c++ - 检测私有(private)成员的存在

c++ - 没有临时实例的参数转发

c++ - C++14 中通用 lambda 函数的递归

c++ - 为什么我不能在 for 循环的第一条语句中包含 2 个变量

c++ - 使用 constexpr 初始化非常量静态字符串

c++ - WM_MOUSEMOVE - 打包 x 和 y 位置

eclipse - Eclipse CDT 中的 C++14 语法可以编译但标记为语法错误(索引器)

c++ - 在 C++ 中修复观察者设计模式

C++文件输入问题

c++ - 为什么这段代码涉及使用对临时段错误的引用,尽管它似乎正确地管理了生命周期?