logo

Inicializar vector en C++

Un vector puede almacenar múltiples valores de datos como matrices, pero solo puede almacenar referencias de objetos y no tipos de datos primitivos. Almacenan la referencia de un objeto, lo que significa que apuntan a los objetos que contienen los datos, en lugar de almacenarlos. A diferencia de una matriz, los vectores no necesitan inicializarse con tamaño. Tienen la flexibilidad de ajustarse según la cantidad de referencias de objetos, lo cual es posible porque su almacenamiento es manejado automáticamente por el contenedor. El contenedor mantendrá una copia interna de alloc, que se utiliza para asignar almacenamiento de por vida. Los vectores se pueden ubicar y recorrer mediante iteradores, por lo que se colocan en un almacenamiento contiguo. Vector también tiene características de seguridad, que evitan que los programas fallen, a diferencia de Array. Podemos dar espacio de reserva a vectores, pero no a matrices. Una matriz no es una clase, pero un vector es una clase. En vector, los elementos se pueden eliminar, pero no en matrices.

Con la 'clase de colección' principal, el vector se envía en forma de clase de plantilla. La matriz es la estructura de datos de nivel inferior con sus propiedades específicas. Los vectores tienen funciones y constructores; no están basados ​​en índices. Son lo opuesto a los Arrays, que son estructuras de datos basadas en índices. Aquí, la dirección más baja se proporciona al primer elemento y la dirección más alta se proporciona al último elemento. Vector se utiliza para la inserción y eliminación de un objeto, mientras que las matrices se utilizan para el acceso frecuente a objetos. Las matrices son estructuras de datos que ahorran memoria, mientras que Vector utiliza mucha más memoria a cambio para administrar el almacenamiento y crecer dinámicamente. Vector tarda más tiempo en acceder a los elementos, pero este no es el caso con los Arrays.

Hay cuatro formas de inicializar un vectores en C++ :

  • Ingresando los valores uno por uno
  • Usando un constructor sobrecargado de la clase vectorial
  • Con la ayuda de matrices.
  • Usando otro vector inicializado

Ingresando los valores uno por uno -

Todos los elementos de un vector se pueden insertar uno por uno utilizando el método de clase de vector 'push_back'.

Algoritmo

 Begin Declare v of vector type. Then we call push_back() function. This is done to insert values into vector v. Then we print 'Vector elements: 
'. ' for (int a: v) print all the elements of variable a.' 

Código -

 #include #include using namespace std; int main() { vector vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); vec.push_back(6); vec.push_back(7); vec.push_back(8); vec.push_back(9); vec.push_back(101); for (int i = 0; i <vec.size(); i++) { cout << vec[i] ' '; } return 0; < pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/62/initialize-vector-c.webp" alt="Initialize Vector in C++"> <h3>Using an overloaded constructor -</h3> <p>When a vector has multiple elements with the same values, then we use this method.</p> <p>By using an overloaded constructor of the vector class -</p> <p>This method is mainly used when a vector is filled with multiple elements with the same value.</p> <p> <strong>Algorithm</strong> </p> <pre> Begin First, we initialize a variable say &apos;s&apos;. Then we have to create a vector say &apos;v&apos; with size&apos;s&apos;. Then we initialize vector v1. Then initialize v2 by v1. Then we print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { int elements = 12; vector vec(elements, 8); for (int i = 0; i <vec.size(); i++) { cout << vec[i] ' 
'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 8 8 8 8 8 8 8 8 8 8 8 8 </pre> <h3>By the help of arrays -</h3> <p>We pass an array to the constructor of the vector class. The Array contains the elements which will fill the vector.</p> <p> <strong>Algorithm -</strong> </p> <pre> Begin First, we create a vector say v. Then, we initialize the vector. In the end, print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { vector vectr{9,8,7,6,5,4,3,2,1,0}; for (int i = 0; i <vectr.size(); i++) { cout << vectr[i] ' 
'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 9 8 7 6 5 4 3 2 1 0 </pre> <h3>Using another initialized vector -</h3> <p>Here, we have to pass the begin() and end() iterators of an initialized vector to a vector class constructor. Then we initialize a new vector and fill it with the old vector.</p> <p> <strong>Algorithm -</strong> </p> <pre> Begin First, we have to create a vector v1. Then, we have to initialize vector v1 by an array. Then we initialize vector v2 by v1. We have to print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { vector vec_1{1,2,3,4,5,6,7,8}; vector vec_2(vec_1.begin(), vec_1.end()); for (int i = 0; i <vec_2.size(); i++) { cout << vec_2[i] ' 
'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 1 2 3 4 5 6 7 8 </pre> <hr></vec_2.size();></pre></vectr.size();></pre></vec.size();></pre></vec.size();>

Código -

 #include #include using namespace std; int main() { int elements = 12; vector vec(elements, 8); for (int i = 0; i <vec.size(); i++) { cout << vec[i] \' 
\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 8 8 8 8 8 8 8 8 8 8 8 8 </pre> <h3>By the help of arrays -</h3> <p>We pass an array to the constructor of the vector class. The Array contains the elements which will fill the vector.</p> <p> <strong>Algorithm -</strong> </p> <pre> Begin First, we create a vector say v. Then, we initialize the vector. In the end, print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { vector vectr{9,8,7,6,5,4,3,2,1,0}; for (int i = 0; i <vectr.size(); i++) { cout << vectr[i] \' 
\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 9 8 7 6 5 4 3 2 1 0 </pre> <h3>Using another initialized vector -</h3> <p>Here, we have to pass the begin() and end() iterators of an initialized vector to a vector class constructor. Then we initialize a new vector and fill it with the old vector.</p> <p> <strong>Algorithm -</strong> </p> <pre> Begin First, we have to create a vector v1. Then, we have to initialize vector v1 by an array. Then we initialize vector v2 by v1. We have to print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { vector vec_1{1,2,3,4,5,6,7,8}; vector vec_2(vec_1.begin(), vec_1.end()); for (int i = 0; i <vec_2.size(); i++) { cout << vec_2[i] \' 
\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 1 2 3 4 5 6 7 8 </pre> <hr></vec_2.size();></pre></vectr.size();></pre></vec.size();>

Con la ayuda de matrices -

Pasamos una matriz al constructor de la clase vectorial. La matriz contiene los elementos que llenarán el vector.

Algoritmo -

 Begin First, we create a vector say v. Then, we initialize the vector. In the end, print the elements. End. 

Código -

 #include #include using namespace std; int main() { vector vectr{9,8,7,6,5,4,3,2,1,0}; for (int i = 0; i <vectr.size(); i++) { cout << vectr[i] \' 
\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 9 8 7 6 5 4 3 2 1 0 </pre> <h3>Using another initialized vector -</h3> <p>Here, we have to pass the begin() and end() iterators of an initialized vector to a vector class constructor. Then we initialize a new vector and fill it with the old vector.</p> <p> <strong>Algorithm -</strong> </p> <pre> Begin First, we have to create a vector v1. Then, we have to initialize vector v1 by an array. Then we initialize vector v2 by v1. We have to print the elements. End. </pre> <p> <strong>Code -</strong> </p> <pre> #include #include using namespace std; int main() { vector vec_1{1,2,3,4,5,6,7,8}; vector vec_2(vec_1.begin(), vec_1.end()); for (int i = 0; i <vec_2.size(); i++) { cout << vec_2[i] \' 
\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 1 2 3 4 5 6 7 8 </pre> <hr></vec_2.size();></pre></vectr.size();>

Usando otro vector inicializado -

Aquí, tenemos que pasar los iteradores start() y end() de un vector inicializado a un constructor de clase vectorial. Luego inicializamos un nuevo vector y lo rellenamos con el vector antiguo.

Algoritmo -

 Begin First, we have to create a vector v1. Then, we have to initialize vector v1 by an array. Then we initialize vector v2 by v1. We have to print the elements. End. 

Código -

 #include #include using namespace std; int main() { vector vec_1{1,2,3,4,5,6,7,8}; vector vec_2(vec_1.begin(), vec_1.end()); for (int i = 0; i <vec_2.size(); i++) { cout << vec_2[i] \\' 
\\'; } return 0; < pre> <p> <strong>Output</strong> </p> <pre> 1 2 3 4 5 6 7 8 </pre> <hr></vec_2.size();>