備忘録

備忘録

C++でLINQを使う方法(cpplinqの使い方)

Ⅰ. はじめに

タイトルの通り「C++LINQを使う方法(cpplinqの使い方)」です。

Ⅱ. 使い方

1. GitHubから cpplinq.hpp をダウンロードする

https://github.com/mrange/cpplinq

2. サンプルプログラムを書く
#include <iostream>
#include <list>
#include <algorithm>
#include <string>
#include "cpplinq.hpp"
using namespace cpplinq;

class Human
{
public:
  std::string Name;
  int Age;

  Human(std::string name, int age)
  {
    this->Name = name;
    this->Age = age;
  }
};

int main()
{
  auto humans = std::list<Human>();
  humans.emplace_back(Human("name001", 9));
  humans.emplace_back(Human("name002", 10));
  humans.emplace_back(Human("name003", 11));

  humans = from(humans)
    >> where([](Human x) {return x.Age >= 10; })
    >> orderby([](Human x) {return -x.Age; })
    >> to_list();

  std::for_each(humans.begin(), humans.end(), [](Human x)
  {
    std::cout << x.Name << "," << x.Age << std::endl;
  });
}
実行結果

f:id:kagasu:20180411202657p:plain