簡體   English   中英

獲取 STL 向量中大於某個值的元素的所有位置

[英]Get all positions of elements in STL vector that are greater than a value

我想知道如何找到驗證某個條件(例如大於)的元素的索引位置。 例如,如果我有一個 int 值向量

vector<int> V;

V 包含值3 2 5 8 2 1 10 4 7

並且我想獲取大於 5 的元素的所有索引位置。我知道std::find_if但根據文檔,它只找到滿足條件的第一個元素。

循環std::find_if ,從上次停止的位置開始。

樣品( 見工作 ):

std::vector<size_t> results;

auto it = std::find_if(std::begin(v), std::end(v), [](int i){return i > 5;});
while (it != std::end(v)) {
   results.emplace_back(std::distance(std::begin(v), it));
   it = std::find_if(std::next(it), std::end(v), [](int i){return i > 5;});
}

首先,我們使用第一個結果設置迭代器。 如果找不到,則while循環永遠不會執行。 否則,存儲索引位置( std::distance基本上是更通用的it - std::begin(v) ),並繼續搜索。

我想我會使用std::copy_if

std::vector<int> x{3, 2, 5, 8, 2, 1, 10, 4, 7};
std::vector<size_t> y(x.size());

std::iota(y.begin(), y.end(), 0);
std::copy_if(y.begin(), y.end(), 
             std::ostream_iterator<size_t>(std::cout, " "), 
             [&](size_t i) { return x[i] > 5; });

對我來說,這給出了3 6 8x ,8,10和7的指數 - 正是我們想要的。

如果您堅持使用C ++ 98/03編譯器/庫,那么您將使用std::remove_copy_if (並反轉比較的意義)。 在這種情況下,您顯然無法使用lambda進行比較。

只是為了好玩, transform_if算法:

#include <vector>
#include <iterator>
#include <algorithm>
#include <iostream>

template<typename InputIterator, typename OutputIterator,
    typename UnaryPredicate, typename UnaryFunction>
OutputIterator
transform_if (InputIterator first, InputIterator last,
    OutputIterator result, UnaryPredicate pred,
    UnaryFunction func)
{
    for (; first != last; ++first, ++result)
        if (pred(*first))
            *result = func(*first);
    return result;
}

int main()
{
    std::vector<int> x {3, 2, 5, 8, 2, 1, 10, 4, 7};
    std::vector<size_t> indices;

    size_t index = 0;
    transform_if(x.begin(), x.end(), std::back_inserter(indices),
        [&](int i){ return ++index, i > 5; },
        [&](int){ return index-1; });

    std::copy(indices.begin(), indices.end(),
              std::ostream_iterator<size_t>(std::cout, " "));
}

輸出: 3 6 8

在 C++20 中,使用視圖,您可能會這樣做

std::ranges::iota_view{0, (int)v.size()}
    | std::ranges::views::filter([&v](int i){ return v[i] > 5; })

演示

暫無
暫無

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

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