簡體   English   中英

提供正確的 std::copy_if 謂詞

[英]Providing a correct std::copy_if predicate

示例程序的目的是使用std::copy_if將每三個項目從source復制到目標。 根據參考,只要謂詞返回 true,就應該進行復制,但下面的代碼並非如此。

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

using std::vector;

int main(int argc, char** agrs){
    vector<double> source(15, 0.5);
    vector<double> target(15, 1.1);
    int index = 0;
    std::copy_if(
        source.begin(),source.end(),target.begin(),
        [&](double number){
            index = ((index + 1) % 3);
            std::cout << "["<< index << "]->" << (0 == index) << "\t";
            return (0 == index);
        }
    );
    std::cout << std::endl;

    std::for_each(source.begin(),source.end(),[](double value){
            std::cout << "["<< value << "]\t";
    });
    std::cout << std::endl;
    std::for_each(target.begin(),target.end(),[](double value){
            std::cout << "["<< value << "]\t";
    });
    std::cout << std::endl;
    return 0;
}

output如下:

[1]->0  [2]->0  [0]->1  [1]->0  [2]->0  [0]->1  [1]->0  [2]->0  [0]->1  [1]->0  [2]->0  [0]->1  [1]->0  [2]->0  [0]->1
[0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [0.5]
[0.5]   [0.5]   [0.5]   [0.5]   [0.5]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]   [1.1]

第一行顯示實際復制以及 output 謂詞的返回值。 第二行是源向量,第三行是目標向量。

期望根據謂詞復制每個第三個元素是公平的,但事實並非如此?

這是為什么? 如何固定邏輯以實現其預期目的?

不幸的是,有時 cplusplus 有錯誤/誤導性的信息。 他們寫:

結果

Output 迭代器到存儲結果序列的范圍的初始 position。 該范圍包括與 [first,last) 一樣多的元素。

這是錯誤的。 output 范圍的元素數量與謂詞返回的數量一樣多true 在這種情況下,不會復制其他的,並且目標迭代器不會遞增。 copy_if的工作方式與您的示例中的預期一樣。

我建議這個參考: https://en.cppreference.com/w/cpp/algorithm/copy

它也沒有明確提到 output 迭代器僅在實際復制元素時才高級。 但它也不會 state 否則。 查看可能的實現應該會讓事情更清楚:

 template<class InputIt, class OutputIt, class UnaryPredicate> OutputIt copy_if(InputIt first, InputIt last, OutputIt d_first, UnaryPredicate pred) { while (first;= last) { if (pred(*first)) *d_first++ = *first; first++; } return d_first; }

您可以看到d_first僅在pred(*first)返回true時遞增。

暫無
暫無

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

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