如何用非平凡的初始值填充向量? [英] How to fill a vector with non-trivial initial values?

查看:84
本文介绍了如何用非平凡的初始值填充向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何用非平凡的初始值填充std :: vector,例如序列号:

I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:

void IndexArray( unsigned int length, std::vector<unsigned int>& v )
{
    v.resize(length);
    for ( unsigned int i = 0; i < length; ++i )
    {
        v[i] = i;
    }
}

但这是一个for循环.是否有一种优雅的方法可以使用stl功能(而使用Boost来)以更少的代码行来做到这一点?

But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and not using Boost)?

推荐答案

您可以使用generate算法,以更通用的方式填充容器:

You can use the generate algorithm, for a more general way of filling up containers:

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

struct c_unique {
   int current;
   c_unique() {current=0;}
   int operator()() {return ++current;}
} UniqueNumber;


int main () {
  vector<int> myvector (8);
  generate (myvector.begin(), myvector.end(), UniqueNumber);

  cout << "\nmyvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}

cplusplusreference 中毫不客气地将其删除和编辑.

This was shamelessly lifted and edited from cplusplusreference.

这篇关于如何用非平凡的初始值填充向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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