Checking if all elements of a vector are equal in C++(在 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 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++ 中检查向量的所有元素是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中检查向量的所有元素是否相等


基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 从 std::cin 读取密码 2021-01-01