Skip to main content

6.2) Creation Of Vectors


vector<int> a;                // empty vector of integers
vector<int> b(10);            // 10 integers, all 0
vector<int> c(5, -1);         // 5 integers, all -1
vector<int> d(c);             // d will be a copy of c
vector<string> p;             // empty vector of strings
vector<string> q(5, "xyz");   // 5 strings, all "xyz"
vector<string> r(q);          //  r will be a copy of q
  • Vectors are made available via #include <vector>
  • The type of value to be stored is specified inside <>; this can even be another vector!
  • Vectors can be declared empty or with an initial size and can grow or shrink after creation; declaring the initial size is more efficient than growing a vector from empty and should be done if you have a good idea of what your eventual storage requirements will be
  • Elements are initialized to a default value, unlike arrays (see later); a specific initial value can also be provided at creation time