Cómo inicializar un vector de punteros [cerrado]

I am working on a C++ program, and I need to initialize a vector of pointers. I know how to initialize a vector, but if someone could show me how to initialize it as a vector filled with pointers that would be great!

preguntado el 01 de febrero de 12 a las 04:02

1 Respuestas

A zero-size vector of pointers:

std::vector<int*> empty;

A vector of NULL pointers:

std::vector<int*> nulled(10);

A vector of pointers to newly allocated objects (not really initialization though):

std::vector<int*> stuff;
for( int i = 0; i < 10; ++i )
    stuff.push_back(new int(i));

Initializing a vector of pointers to newly allocated objects (needs C++11):

std::vector<int*> widgets{ new int(0), new int(1), new int(17) };

A smarter version of #3:

std::vector<std::unique_ptr<int>> stuff;
for( int i = 0; i < 10; ++i )
    stuff.emplace_back(new int(i));

Respondido 21 Abr '13, 18:04

Thanks guys, this helps! - Joshua Vaughan

Boo for exception unsafety! :-) - Kerrek SB

emplace_back doesn't buy you anything with scalar types such as pointers. - fredoverflow

@FredOverflow: unique_ptr's constructor is explicit, so you either need to use emplace_back or stuff.push_back(std::unique_ptr<int>(new int(i)));. Between the two, emplace_back es mucho más limpio. - James McNellis

@JamesMcNellis I stand corrected. - fredoverflow

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.