如何在C++中为类似functor的C#容器应用算法?

Cha*_*han 2 c# c++

在C++中为集合或容器应用算法,我重载了operator().例如,为容器生成随机数:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>

using namespace std;

class rnd_gen {
public:
    rnd_gen( int lo, int up ) : lo( lo ), up( up ) {

    }

    int operator()() const {
        return lo + rand() % up;
    }

private:
    int lo;
    int up;
};

int main() {
    vector<int> vt;
    vt.push_back( 3 );
    vt.push_back( 1 );
    vt.push_back( 2 );
    generate( vt.begin(), vt.end(), rnd_gen( 10, 100 ) );
}
Run Code Online (Sandbox Code Playgroud)

是否可以在没有明确编写for循环的情况下执行这些操作?或者是C#中最接近的等效方法.

谢谢,

LBu*_*kin 5

是的,在C#中,使用LINQ执行此操作的规范方法是:

Random r = new Random();
List<int> randomInts = Enumerable.Repeat(0,3) // create 3 dummy placeholder values
                                 .Select( x => r.Next(10,100) )
                                 .ToList();
Run Code Online (Sandbox Code Playgroud)

打破上面的代码:

Enumerable.Range(0,3)          => creates sequence of value '0' repeated 3 times
.Select( x => r.Next(10,100) ) => uses the Select (projection) operator 
                                  with a lambda expression to calculate 3 random
                                  values (the value of x is ignored)
.ToList()                      => materializes the resulting sequence as List<int>
Run Code Online (Sandbox Code Playgroud)

在.NET中,LINQ(语言集成查询)提供了一组丰富的运算符来组合和操作序列,并在代码中表示针对集合的查询.