检查向量的所有元素在C ++中是否相等 [英] Checking if all elements of a vector are equal in C++

查看:141
本文介绍了检查向量的所有元素在C ++中是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个值向量,并想检查它们是否都相同,那么在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 al 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的阅读,我看到了其他答案,例如使用一组或find_if算法。那么最有效的方法是什么?为什么?我想我的方法不是最好的方法,因为它涉及到对每个元素进行排序,然后调整向量的大小-但也许我错了。

However reading about 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.

谢谢,
Ben。

Thanks, Ben.

推荐答案

您需要不要使用 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 ++中是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆