这是 std::array 在常规数组上的一个有趣用例:在某个地方我无法更改语法以适用于常规数组(或者我已经说服了自己)。
#include <iostream>
#include <algorithm>
#include <array>
#include <map>
using namespace std;
int main()
{
int n, c = 0; cin >> n;
array<int, 3> tri;
map<array<int, 3>, int> freq;
while (n--)
{
cin >> tri[0] >> tri[1] >> tri[2];
sort(begin(tri), end(tri));
freq[tri]++;
}
for (auto i : freq)
{
cout << &i.first << ' ' << i.second << endl;
if (i.second == 1)
{
c++;
}
}
cout << c;
}
当我尝试用常规 int[3]
切换 std::array 时, map 模板参数为 map<int*, int>
, 程序似乎制作 map freq
再利用 tri
,即使我把它放在 while 循环中,就像优化一样。
请注意,对于 map<int*, int>
打印 map 内容的语句是
cout << i.first << ' ' << i.second << endl;
我的问题是,为什么 std::array 在这里没有遇到技术困难? freq[tri]++
隐藏的魔法是什么?声明?
最佳答案
std::array
在这里没有问题的原因是因为它不像原始数组那样衰减为指针。因此,当您使用 std::array
时,您会在 map 中获得它的拷贝,该拷贝对于 map 是唯一的。当您使用原始数组时,您会得到一个指向该数组的指针,并且您必须动态分配它们以获得不同的数组,因为您将指针而不是数组复制到映射中。
关于c++ - 有趣的用例,其中常规数组不能代替 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46502981/