c++ - 在无效循环 cout 操作期间,元素自动插入到 std::map

标签 c++ visual-c++

<分区>

#include<iostream>
#include<map>
using namespace std;
int main() 
{
    map<int, string> sample;
    for (int i = 5; i > 0; i--)
        sample[i] = 'i' + i;
    map<int, string>::iterator i = sample.begin();
    for (int j = 1; j <= 10; j++) 
    {
        cout << sample[j] << endl;
    }
    for (; i != sample.end(); i++)
        cout << i->first;
    cout << "Size is :" << sample.size();
}

我运行这个程序是为了了解更多关于 std::map 的信息,即我得到的 map 大小为 10,请引用下面的输出截图。

enter image description here

谁能解释一下为什么 std::map 在无效循环显示函数中自动扩展。

最佳答案

std::map::operator [key] 等同于 (*((this->insert(make_pair(key, mapped_type()))).first))。第二个,因此如果元素不存在则插入一个默认值。

您必须使用 atfind 才能在 map 中不插入元素,或使用迭代器。

关于c++ - 在无效循环 cout 操作期间,元素自动插入到 std::map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368573/

相关文章:

c++ - VertexBuffer 混合顶点

c++ - 奇怪的加法——统计一个词在一个文件中出现的次数

c++ - 执行内存分配以存储中断处理程序中获取的数据

c++ - CTime初始化

c++ - 符号 (&) 在 .rc 文件中的含义

c++ - 概率和随机数

c++ - 如何使用 clang::TreeTransform?

visual-c++ - 如何从消息框获取答案

c++ - 使用读取 [ebp+4] 的 MSVC 内联 asm 移植到 64 位

c++ - 异常在 MSVC 中的析构函数中抛出异常