有条件地检验向量元素的相等性
conditionally testing for equality of vector's elements
虽然看起来很简单,但我不确定最有效的方法。
我有两个向量:
std::vector<bool> a;
std::vector<int> b;
a.size()
必然等于b.size()
.
a
中的每个布尔值对应于 b
中的一个整数。我想创建一个函数:
bool test(std::vector<bool> a, std::vector<int> b);
如果 a
中的值相等,此函数将返回true
。但是,它只考虑a
中与b
中的true
值对应的值。
我可以这样做:
bool test(std::vector<int> a, std::vector<bool> b){
int x;
unsigned int i;
for(i = 0; i < a.size(); ++i){
if(b.at(i) == true){
x = a.at(i);
break;
}
}
for(i = 0; i < a.size(); ++i){
if(b.at(i) == true){
if(a.at(i) != x){
return false;
}
}
}
return true;
}
但是我必须创建两个循环。虽然第一个循环会在第一个真实值处停止,但有没有更好的方法?
您的解决方案对我来说看起来足够好:
- 无论如何,每个循环都会做不同的事情(所以你不必担心重复)
- 不要使用使代码复杂化的无关变量或标志。
我看到的唯一问题是:
- 您从 0 开始第二个循环,而不是从上次中断的地方开始。
- 做
if(condition == true)
是非常丑陋的。只是做if(condition)
。
bool test(std::vector<int> a, std::vector<bool> b){
int x;
unsigned i;
for(i = 0; i < a.size(); i++){
if(b.at(i)){
x = a.at(i);
break;
}
}
for(i++; i < a.size(); i++){
if(b.at(i)){
if(a.at(i) != x){
return false;
}
}
return true;
}
如果您
还记得是否在b
中看到过第一个true
元素,则可以在一个循环中执行此操作。此外,还应通过引用获取a
和b
参数,以避免不必要的复制。最后,如果您知道向量的索引始终在有效范围内(即在 0 和 vector.size() - 1 之间,包括 0 和 vector.size() - 1),您可以使用 operator[]
而不是 at
,并获得更好的性能(at
进行范围检查,而operator[]
则不这样做)。以下是考虑上述所有要点的test
函数的修改版本:
bool test(std::vector<int> const& a, std::vector<bool> const& b){
int x;
bool first = true;
for(unsigned i = 0, n = a.size(); i != n; ++i){
if( b[i] ){
if( first ) {
x = a[i];
first = false;
}
else if( x != a[i] ) {
return false;
}
}
}
return true;
}
如果你知道 a.size() == b.size() 只需创建一个循环,在每次迭代中同时将 'a' 元素与 'b' 元素进行比较。 一旦你看到a[i] != b[i],那么你就知道容器不匹配,你可以突破。
我不是 100% 确定我知道你想做什么,但一旦你知道你的大小相等,就会直接比较
std::equal(a.begin(), a.end(), b.begin(), std::equal_to<bool>())
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 用函子检验向量的每个元素
- 有条件地检验向量元素的相等性