在 C++ 中检查向量的所有元素是否相等

Checking if all elements of a vector are equal in C++(在 C++ 中检查向量的所有元素是否相等)
本文介绍了在 C++ 中检查向量的所有元素是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

如果我有一个值向量并想检查它们是否都相同,那么在 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 上阅读,我看到其他答案,例如使用 setfind_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++ 中检查向量的所有元素是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)