在地图上使用 foreach 的意外副本 [英] unexpected copies with foreach over a map

查看:28
本文介绍了在地图上使用 foreach 的意外副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历地图的条目,但得到了意外的副本.这是程序:

I am trying to loop over the entries of a map, and I get unexpected copies. Here is the program:

#include <iostream>
#include <map>
#include <string>

struct X
{
    X()
    {
        std::cout << "default constructor
";
    }

    X(const X&)
    {
        std::cout << "copy constructor
";
    }
};

int main()
{
    std::map<int, X> numbers = {{1, X()}, {2, X()}, {3, X()}};
    std::cout << "STARTING LOOP
";
    for (const std::pair<int, X>& p : numbers)
    {
    }
    std::cout << "ENDING LOOP
";
}

这是输出:

default constructor
copy constructor
default constructor
copy constructor
default constructor
copy constructor
copy constructor
copy constructor
copy constructor
STARTING LOOP
copy constructor
copy constructor
copy constructor
ENDING LOOP

为什么我在循环中得到三个副本?如果我使用类型推断,副本就会消失:

Why do I get three copies inside the loop? The copies disappear if I use type inference:

for (auto&& p : numbers)
{
}

这是怎么回事?

推荐答案

map的值类型为pair;所以你的循环需要将 pair 转换为 pair,复制键和值,给你一个参考类型.

The value type of map<K,V> is pair<const K,V>; so your loop needs to convert pair<const int,X> to pair<int,X>, copying both the key and the value, to give you a reference to that type.

使用正确的类型(明确指定,或使用 auto 推断)将删除副本.

Using the correct type (specified explicitly, or deduced with auto) will remove the copies.

这篇关于在地图上使用 foreach 的意外副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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