简体   繁体   中英

finding position of element of a vector that satisfies given condition in c++

I am learning c++, and I want to implement the following python codes in c++:

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 and B are both vectors of the same length. In C++, I know how to declare and initialize A and B using vector , and implement the middle "do something part" to both A and B, but I don't know how to compare them and check if A has elements larger than B , and find the index of the element where this occurs.

C++ has a rich set of utility functions in <algorithm> header. In case of your problem:

  • C = np.where(A>B)[0] could be translated to C++ as follows:

     std::size_t index = 0; auto pos = std::find_if(A.cbegin(), A.cend(), [&index, &B](const int &i){ return i > B[index++]; }); 
  • C = A>B also could be rewritten in C++ as follows:

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

So, it altogether could be simplified as below:

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

Also note that in this code pos is of type vector<int>::iterator which points to the first match. In order to convert it to an integer index, you can use std::distance function.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM