如果我有一个值向量并且想要检查它们是否都相同,那么在 C++ 中有效执行此操作的最佳方法是什么?如果我用其他语言(例如 R)进行编程,我的想法是仅返回容器的唯一元素,然后如果唯一元素的长度大于 1,我知道所有元素不可能相同。在 C++ 中,可以这样完成:
//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;
}
然而,在互联网上阅读,我看到其他答案,例如使用set
or the find_if
算法。那么最有效的方法是什么?为什么?我想我的方法不是最好的方法,因为它涉及对每个元素进行排序,然后调整向量的大小 - 但也许我错了。
你不需要使用std::sort
。可以用更简单的方式完成:
if ( std::adjacent_find( myvector.begin(), myvector.end(), std::not_equal_to<>() ) == myvector.end() )
{
std::cout << "All elements are equal each other" << std::endl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)