vectores unidimensionales tipos programacion llenar imprimir ejemplos dev como arreglos c++ stl

c++ - unidimensionales - imprimir un vector en c



¿Cómo llenar un vector con valores iniciales no triviales? (6)

Sé cómo llenar un std :: vector con valores iniciales no triviales, por ejemplo, números de secuencia:

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

Pero esto es un bucle for. ¿Hay una manera elegante de hacer esto con menos líneas de código usando la funcionalidad stl (y no usando Boost)?


Normalmente voy con std::generate plus un generador simple:

template <typename T> struct gen { T x; gen(T seed) : x(seed) { } T operator ()() { return x++; } }; generate(a.begin(), a.end(), gen<int>(0));


Puede usar el algoritmo de generación para una forma más general de llenar contenedores:

#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; }

Esto fue descaradamente levantado y editado desde cplusplusreference .


Si está utilizando SGI STL (o un derivado, como STLPort), puede usar iota . :-)

void IndexArray(unsigned int length, vector<unsigned int>& v) { vector<unsigned int>(length).swap(v); iota(v.begin(), v.end(), 0); }


Si tiene una matriz de estilo C, puede usar std: copy, por ejemplo,

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));


También hay una función iota() en adobe.ASL , (y un value_iterator también). En boost, hay un cuenta-puntuadores , y sospecho que hay otras formas de generar secuencias de números sobre la marcha en boost.


Sé que esto ya ha sido respondido, pero prefiero la función "llenar" en la biblioteca de algoritmos, ya que me parece más intuitivo leer:

// 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; }

Esto también fue descaradamente eliminado de cplusplusreference .