为什么 std::generate 将与 lambda 生成器一起使用,而 std::fill 则不能

Why std::generate will work with lambda generator and std::fill will not?

本文关键字:std 不能 fill 将与 generate lambda 为什么 一起      更新时间:2023-10-16

我偶然发现了这个网站:http://www2.research.att.com/~bs/C++0xFAQ.html#lambda 他们解释lambda函数的地方。我尝试使用提供的示例,即:

    vector<int> indices( notImportantNumber );
    int count = 0;
    fill(indices.begin(), indices.end(), [&](){ return ++count; });

和类似

    generate(indices.begin(), indices.end(), [&](){ return ++count; });

虽然,当我尝试使用带有填充的示例时,我不断收到此错误:

错误

1 错误 C2440:"=":无法从"常量"转换 'anonymous-namespace'::' to 'long' c:\program files\Microsoft Visual Studio 10.0\VC\include\xutility 2692

有人知道为什么会这样吗?在 std::fill() 的声明中,没有函子作为最后一个参数。

这是该网站上的错误。 std::fill需要一个值来填充,而不是一个可调用的值。

因为std::fill不希望函子作为最后一个参数 - 请参阅参考

将给定值分配给范围 [第一个、最后一个] 中的元素。

它只需要一个元素,该元素将分配给指定范围内的每个项目。

使用 std::remove_if 和更多 STL 函数的示例:

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

int main()
{
    // using STL you can write code
    // that is more expressive and has less (visible) for loops
    // using a set is more maintainable, but just checking a few values
    // with ==5 && ==7 is faster.
    std::set<int> numbers_to_remove{ 5,7 };
    // initialize a list of odd numbers
    std::vector<int> values(5);
    // last argument to generate is a lambda function
    // https://en.cppreference.com/w/cpp/language/lambda
    int odd_number{ 1 };
    std::generate(values.begin(), values.end(), [&] { return odd_number += 2; });
    // remove the items from the vector
    // remove_if will only move the items to delete to the end.
    // so one more call to erase is needed to cleanup the vector.
    auto erase_it = std::remove_if(values.begin(),values.end(), [&](const int value) 
    { 
        return numbers_to_remove.find(value) != numbers_to_remove.end(); 
    });
    // or if you don't want to use a set
    // auto erase_it = std::remove_if(values.begin(), values.end(), [](const int value) { return (value==5) || (value==7)}); // using explicit compares.
    values.erase(erase_it,values.end());
    // loop over all the values using a range based for loop.
    // this is safer then using indices, you can't go out of range.
    // const because you don't want to change the values in the loop
    // https://en.cppreference.com/w/cpp/language/range-for
    for (const int value : values)
    {
        std::cout << value << " ";
    }
    return 0;
}