15

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

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)用更少的代码行来做到这一点?

4

6 回答 6

15

您可以使用生成算法来获得更通用的填充容器的方法:

#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无耻地提升和编辑的。

于 2008-10-16T08:28:10.187 回答
5

我通常会std::generate加上一个简单的生成器:

template <typename T>
struct gen {
    T x;
    gen(T seed) : x(seed) { }

    T operator ()() { return x++; }
};

generate(a.begin(), a.end(), gen<int>(0));
于 2008-10-16T11:13:18.090 回答
4

如果您使用的是 SGI STL(或衍生产品,例如 STLPort),您可以使用iota. :-)

void IndexArray(unsigned int length, vector<unsigned int>& v)
{
    vector<unsigned int>(length).swap(v);
    iota(v.begin(), v.end(), 0);
}
于 2008-10-16T08:39:03.940 回答
2

adobe.ASL中还有一个iota()函数,(还有一个value_iterator)。在 boost 中,有一个count_iterator,我怀疑还有其他一些方法可以在 boost 中动态生成数字序列。

于 2008-10-16T12:00:09.243 回答
1

我知道这已经得到解答,但我更喜欢算法库中的“填充”函数,因为它对我来说似乎更直观:

// fill algorithm example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main () {
  vector<int> myvector (8);                       // myvector: 0 0 0 0 0 0 0 0

  fill (myvector.begin(),myvector.begin()+4,5);   // myvector: 5 5 5 5 0 0 0 0
  fill (myvector.begin()+3,myvector.end()-2,8);   // myvector: 5 5 5 8 8 8 0 0

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

  cout << endl;

  return 0;
}

这也无耻地从cplusplusreference中取消了。

于 2011-04-04T15:22:28.167 回答
0

如果你有一个 C 风格的数组,你可以使用 std:copy,例如,

int c_array[] = {3,4,5};

const int* pbegin = &c_array[0];
const size_t c_array_size = sizeof(c_array) / sizeof(c_array[0]);
const int* pend  = pbegin + c_array_size;

std::vector<int> v;
v.reserve(c_array_size);
std::copy(pbegin, pend, std:back_inserter(v));
于 2008-10-16T17:01:21.273 回答