簡體   English   中英

在C ++中找到滿足給定條件的向量元素的位置

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

我正在學習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

AB都是相同長度的向量。 在C ++中,我知道如何使用vector聲明和初始化AB ,並實現對AB的中間“做某事”,但是我不知道如何比較它們並檢查A是否具有大於B元素,並找到發生這種情況的元素的索引。

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++]; }); 
  • 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++]; }); 

因此,它可以完全簡化如下:

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

還要注意,在此代碼中pos的類型為vector<int>::iterator ,它指向第一個匹配項。 為了將其轉換為整數索引,可以使用std::distance函數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM