在c中求满足给定条件的向量元素的位置++

2024-04-25 11:44:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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

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


Tags: andto代码声明元素lennpwhere
1条回答
网友
1楼 · 发布于 2024-04-25 11:44:25

C++在^{}头中有丰富的实用函数集。如果您有问题:

    ^ }可以转化为C++:

    std::size_t index = 0;
    auto pos = std::find_if(A.cbegin(), A.cend(), [&index, &B](const int &i){
        return i > B[index++];
    });
    
    >p> ^ }也可以在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++];
    });
    

因此,可以将其简化如下:

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);

还要注意,在这个代码中posvector<int>::iterator类型,它指向第一个匹配项。为了将其转换为整数索引,可以使用std::distance函数。在

std::size_t index = std::distance(A.cbegin(), pos);

相关问题 更多 >