¿Puedo inicializar un vector STL con 10 del mismo entero en una lista de inicializadores?


¿Puedo inicializar un vector STL con 10 del mismo entero en una lista inicializadora? Mis intentos hasta ahora me han fallado.

Author: Xavier, 2012-04-20

6 answers

Creo que te refieres a esto:

struct test {
   std::vector<int> v;
   test(int value) : v( 100, value ) {}
};
 29
Author: David Rodríguez - dribeas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-20 00:51:11

Use el constructor apropiado, que toma un tamaño y un valor predeterminado.

int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
 99
Author: Ed S.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 22:40:39

Si estás usando C++11 y en GCC, puedes hacer esto:

vector<int> myVec () {[0 ... 99] = 1};

Se llama inicialización a distancia y es una extensión solo para GCC.

 6
Author: Mahmoud Al-Qudsi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 22:33:23

Puedes hacer eso con std::vector constructor:

vector(size_type count, 
                 const T& value,
                 const Allocator& alloc = Allocator());

Que toma count y value para ser repetido.

Si quieres usar listas inicializadoras puedes escribir:

const int x = 5;
std::vector<int> vec {x, x, x, x, x, x, x, x, x, x};
 4
Author: Rafał Rawicki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 22:34:31

La lista de inicialización para vector es compatible con C++0x. Si compiló con C++98

int number_of_elements = 10;
int default_value = 1;
std::vector<int> vec(number_of_elements, default_value);
 4
Author: Agus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-20 00:54:06

¿Puedes publicar lo que estás haciendo

 int i = 100;
vector<int> vInts2 (10, i);

vector<int>::iterator iter;
for(iter = vInts2.begin(); iter != vInts2.end(); ++iter)
{
    cout << " i " << (*iter) << endl;
}
 0
Author: nate_weldon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-19 22:32:21