有条件地检验向量元素的相等性

conditionally testing for equality of vector's elements

本文关键字:元素 检验 向量 有条件      更新时间:2023-10-16

虽然看起来很简单,但我不确定最有效的方法。

我有两个向量:

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元素,则可以在一个循环中执行此操作。此外,还应通过引用获取ab参数,以避免不必要的复制。最后,如果您知道向量的索引始终在有效范围内(即在 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>())