在 C++ 中找到满足给定条件的向量元素的位置

Phy*_*ist 1 c++ python pointers vector stdvector

我正在学习c++,我想在c++中实现以下python代码:

C = np.where(A>B)[0]
while len(C)>0:
    d = C[0]
    # do something to A[d] and B[d]
    C = A>B
Run Code Online (Sandbox Code Playgroud)

AB都是相同长度的向量。在 C++ 中,我知道如何声明、初始化AB使用vector,并为 A 和 B 实现中间的“做某事部分”,但我不知道如何比较它们并检查是否A有大于 的元素B,并找到索引发生这种情况的元素。

fro*_*tto 6

C++ 在<algorithm>头文件中有一组丰富的实用函数。如果您遇到问题:

  • C = np.where(A>B)[0] 可以翻译成 C++ 如下:

    std::size_t index = 0;
    auto pos = std::find_if(A.cbegin(), A.cend(), [&index, &B](const int &i){
        return i > B[index++];
    });
    
    Run Code Online (Sandbox Code Playgroud)
  • C = A>B 也可以用 C++ 重写如下:

    std::size_t index = 0;
    auto is_okay = std::all_of(A.cbegin(), A.cend(), [&index, &B](const int &i){
        return i > B[index++];
    });
    
    Run Code Online (Sandbox Code Playgroud)

所以,它完全可以简化如下:

std::vector<int> A = {/* contents of A */};
std::vector<int> B = {/* contents of B */};

std::size_t index;
auto greaterThanB = [&index, &B](const int &i){
    return i > B[index++];
};

// C = np.where(A>B)[0]
index = 0;
auto pos = std::find_if(A.cbegin(), A.cend(), greaterThanB);

// C = A>B
index = 0;
auto is_okay = std::all_of(A.cbegin(), A.cend(), greaterThanB);
Run Code Online (Sandbox Code Playgroud)

另请注意,此代码pos中的类型vector<int>::iterator指向第一个匹配项。为了将其转换为整数索引,您可以使用std::distance函数。

std::size_t index = std::distance(A.cbegin(), pos);
Run Code Online (Sandbox Code Playgroud)