问题描述
如果我有一个值向量并想检查它们是否都相同,那么在 C++ 中有效地执行此操作的最佳方法是什么?如果我使用其他语言(如 R)进行编程,我会想到的一种方式是仅返回容器的唯一元素,然后如果唯一元素的长度大于 1,我知道所有元素不可能相同.在 C++ 中,这可以像这样完成:
If I have a vector of values and want to check that they are all the same, what is the best way to do this in C++ efficiently? If I were programming in some other language like R one way my minds jumps to is to return only the unique elements of the container and then if the length of the unique elements is more than 1, I know all the elements cannot be the same. In C++ this can be done like this:
//build an int vector
std::sort(myvector.begin(), myvector.end());
std::vector<int>::iterator it;
//Use unique algorithm to get the unique values.
it = std::unique(myvector.begin(), myvector.end());
positions.resize(std::distance(myvector.begin(),it));
if (myvector.size() > 1) {
std::cout << "All elements are not the same!" << std::endl;
}
但是在互联网和 SO 上阅读,我看到其他答案,例如使用 set
或 find_if
算法.那么这样做的最有效方法是什么,为什么?我想我的不是最好的方法,因为它涉及对每个元素进行排序,然后调整向量的大小 - 但也许我错了.
However reading on the internet and SO, I see other answers such using a set
or the find_if
algorithm. So what is the most efficient way of doing this and why? I imagine mine is not the best way since it involves sorting every element and then a resizing of the vector - but maybe I'm wrong.
推荐答案
你不需要使用 std::sort
.可以用更简单的方式完成:
You need not to use std::sort
. It can be done in a simpler way:
if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() )
{
std::cout << "All elements are equal each other" << std::endl;
}
这篇关于在 C++ 中检查向量的所有元素是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!