C++17 std::generate的使用

std::generate是“遍历——执行”工具函数的一种

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

int main()
{
  std::vector<std::string> v(4);
  std::generate(v.begin(), v.end(), [i=0]() mutable {
      return ++i % 2 ? "hello" : "world";
  });
  
  for (auto&& s : v) {
    std::cout << s << " ";
  }
  return 0;
}

上面的函数输出是hello world hello world .

std::generate(beginIt, endIt, generator)函数接受起止的迭代器以及一个生成方法。

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.