VOOZH about

URL: https://www.geeksforgeeks.org/cpp/common-subtleties-vector-stls/

⇱ Common Subtleties in  Vector STLs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Common Subtleties in  Vector STLs

Last Updated : 23 Jul, 2025
Prerequisite - Vector Basics Following are some important points that can save time on little things in an interview or an important coding contest.
  1. vector <int> vect(10) vs vector<int> vect[10]
    // Creates a vector vect[] of size 10
    vector <int> vect(10) 
    
    // creates an array of vectors vect[] of size 
    // 10 where each vector has int members
    vector<int> vect[10]
    
  2. resize() and push_back(): After the resize() function has been used on a vector, if push_back() is used on the same vector, the elements being pushed back get added at the end of the resized vector, and not into it.
    Output:
    0 1 2 3 4 0 0 0 0 0
    0 1 2 3 4 0 0 0 0 0 50
  3. clear() function It makes the vector to have zero elements, i.e- no elements and not making the elements to all 0s.
  4. Creating a two dimensional vector
    // This doesn't work
    vector<vector<int>> vect;
    
    // This works fine
    vector< vector <int> > vect; 
    The difference between these two statements is that the first statement has a space between the angular brackets ( > >). Writing without the space doesn't work because >> is an operator in C++.
  5. Passing vectors to functions: When a vector is simply passed to a function, a copy of the vector is created. This might take a lot of time in cases of large vectors.
Output :
10 20
In situations where we don’t actually need to have a copy of the vector, the declaration should be made as follows:
// It is recommended to pass vectors by reference
// wherever possible.
int func(vector<int>& vect)
{

}
Comment