我有四个 std::vector 容器,它们都可能(或可能不)包含元素。我想确定其中哪一个具有最多的元素并随后使用它。
我尝试创建一个 std::map,将它们各自的大小作为键,将对这些容器的引用作为值。然后我在每个 vector 的 size() 上应用 std::max 来计算最大值并通过 std::map 访问它。
显然,一旦至少两个 vector 中的元素数量相同,这就会给我带来麻烦。
谁能想到一个优雅的解决方案?
最佳答案
你想多了。你只有四个 vector 。您可以使用 3 次比较来确定最大的 vector 。就这样做:
std::vector<blah>& max = vector1;
if (max.size() < vector2.size()) max = vector2;
if (max.size() < vector3.size()) max = vector3;
if (max.size() < vector4.size()) max = vector4;
编辑:
现在有了指针!
编辑(280Z28):
现在有引用资料! :)
编辑:
带有引用的版本将不起作用。 Pavel Minaev 在评论中很好地解释了这一点:
That's correct, the code use references. The first line, which declares max, doesn't cause a copy. However, all following lines do cause a copy, because when you write
max = vectorN
, if max is a reference, it doesn't cause the reference to refer to a different vector (a reference cannot be changed to refer to a different object once initialized). Instead, it is the same asmax.operator=(vectorN)
, which simply causesvector1
to be cleared and replaced by elements contained invectorN
, copying them.
指针版本可能是您的最佳选择:它快速、低成本且简单。
std::vector<blah> * max = &vector1;
if (max->size() < vector2.size()) max = &vector2;
if (max->size() < vector3.size()) max = &vector3;
if (max->size() < vector4.size()) max = &vector4;
关于c++ - 从四个 std::vector 对象中选择元素最多的一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1675021/