DEV Community

loading...

Vector in C++

BHAVIN VIRANI
・1 min read

Vectors in C++ are sequence containers representing arrays that can change their size during runtime. They use contiguous storage locations for their elements.

1D Vectors

Syntax

vector<data_type> variable_name
vector<int> vect;


Initializition of vector

Initializition of vector

Iteration on vector

1

  vector<int> vect(n, 10);

    for (int x : vect)
        cout << x << " ";
Enter fullscreen mode Exit fullscreen mode

2

vector<int> vect(n, 10);
// Traversing the vector using
// values directly
// no need to define datatype of vector
    for (auto& it : vect) {

        // Print the values
        cout << it << ' ';
    }
Enter fullscreen mode Exit fullscreen mode

Insert Elements into vector

Insert Elements in vector

Access Elements of vector

Access Elements of vector

deleting vector elements

deleting vector elements

Other functions

Other functions

Why Vector ?

  • Size of arrays are fixed whereas the vectors are resizable i.e they can grow and shrink as vectors are allocated on heap memory. Arrays have to be deallocated explicitly if defined dynamically whereas vectors are automatically de-allocated from heap memory.
  • Reserve space can be given for vector, whereas for arrays you cannot give reserved space.
  • A vector is a class whereas an array is a datatype.
  • Vectors can store any type of objects, whereas an array can store only homogeneous values.

Discussion (0)