简体   繁体   English

当两个 std::map 对象相同时

[英]When two std::map objects are identical

I have two std::map objects that I populate with the same data but the order is different:我有两个使用相同数据填充的std::map对象,但顺序不同:

using TMap = std::map<int, std::wstring>;
using TSourceData = std::vector< std::pair<int, std::wstring> >;

TSourceData gen_source_data(int size)
{
    TSourceData result;
    result.reserve(size);

    for(int i = 0; i < size; ++i)
    {
        result.push_back( std::make_pair(i, std::to_wstring(i)) );
    }

    return result;
}

TMap fill_map(const TSourceData& source)
{
    TMap result;

    auto randomized = source;
    std::random_shuffle(randomized.begin(), randomized.end());

    for(const auto &e : randomized)
    {
        result[e.first] = e.second;
    }

    return result;
}

int main()
{
    auto source = gen_source_data(1000);

    auto m1 = fill_map(source);
    auto m2 = fill_map(source);

    std::wcout << (m1 == m2) << std::endl;
}

In VS2017 it seems to always print 1 so the two maps are equal no matter in what order they were filled.在 VS2017 中,它似乎总是打印1所以无论它们以什么顺序填充,这两个地图都是相等的。 But is it guaranteed to be so?但能保证如此吗? And if so, could you explain why?如果是这样,你能解释一下原因吗?

... so the two maps are equal no matter in what order they were filled. ......所以无论它们以什么顺序填充,这两个地图都是相等的。 But is it guaranteed to be so?但能保证如此吗?

Yes, because std::map is a sorted associative container (usually implemented as a binary tree) its elements are guaranteed to be sorted (regardless of its implementation).是的,因为std::map是一个排序的关联容器(通常实现为二叉树),它的元素保证被排序(不管它的实现如何)。

std::map is an associative container. std::map是一个关联容器。 The difference between a sequential container and an associative container is that:顺序容器和关联容器的区别在于:

Also since std::map is a sorted container, there can be only one possible order for all the keys, so in the absence of duplicates, insertion order for std::map doesn't matter.此外,由于std::map是一个已排序的容器,因此所有键只能有一个可能的顺序,因此在没有重复项的情况下, std::map插入顺序无关紧要。 Similarly, the ordering inside std::unordered_map is determined by the hash of each key, and is again not dependent on the insertion order.类似地, std::unordered_map由每个键的哈希决定,并且再次不依赖于插入顺序。

Notice that you shuffle a vector (a sequential container), then you copy the values into a map .请注意,您打乱了一个vector (一个顺序容器),然后将值复制到map It's impossible to "shuffle" a map , since you do not control the position of the elements there.不可能“洗牌” map ,因为您无法控制那里元素的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM