对于 std::generate,传递的函数可以使用索引吗? [英] for std::generate, can passed function use index?

查看:20
本文介绍了对于 std::generate,传递的函数可以使用索引吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个问题中有点难以表达,所以我会举一个例子.假设我愿意:

A little hard to phrase in a question so I will use an example. Lets say I do:

generate(myvec.begin(), myvec.end(), func())

我可以拥有它以便 func() 可以读取生成的索引吗:

Can I have it so that func() can read the index that generate is up to such that:

int func()
{
   if(index<2)
       return 1;
   else
       return 2;
}

使得 myvec[0]=1, myvec[1]=1, myvec[2]=2, myvec[3]=2,..., myvec[N]=2?

推荐答案

是的,如果你使用一个函数对象作为生成器(正如 juan 指出的,这个解决方案是否能被标准保证工作是有问题的!谨慎行事并使用 Jerry 的方法.):

Yes, if you use a function object as the generator (as juan points out, it is questionable whether this solution is guaranteed to work by the standard! Exercise caution and use Jerry's method.):

class mygenerator {
 public:
  mygenerator() : hits(0) {}

  int operator()() {
      hits++; 
      return (hits <= 2 ? 1 : 2);
  }

 private:
  int hits;
} 

...

mygenerator mg1;
std::generate(myvec.begin(), myvec.end(), mg1);

这篇关于对于 std::generate,传递的函数可以使用索引吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆