我有两个 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;
}
在 VS2017 中,它似乎总是打印 1
因此,无论两个映射以什么顺序填充,它们都是相等的。但事情就一定如此吗?如果是这样,您能解释一下原因吗?
最佳答案
std::map
是一个关联容器。顺序容器和关联容器的区别在于:
- 一个sequential container让您决定元素的位置
- 一个associative container本身决定元素的位置
此外,由于 std::map
是一个排序容器,因此所有键只能有一种可能的顺序,因此在没有重复项的情况下,std::map 的插入顺序
没关系。同样,std::unordered_map
内的顺序由每个键的哈希确定,并且同样不依赖于插入顺序。
请注意,您对 vector
(顺序容器)进行了洗牌,然后将值复制到映射
中。不可能“打乱”map
,因为您无法控制其中元素的位置。
关于c++ - 当两个 std::map 对象相同时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59424684/