Quick Start.

template<
    class T,
    class Allocator = std::allocator<T>
> class vector;

https://youtu.be/HcESuwmlHEY

Basic Usage.

To use Vector on your code, you must include #include <vector>.

#include <vector>
#include <iostream>

int main(void)
{
    std::vector<int> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    for (int i = 0; i < v.size(); i++)
    {
        std::cout << v[i] << std::endl;
    }
    return 0;
	}
output 

1
2
3

<aside> ⚠️ to compilers
g++ -std=98 main.cpp

</aside>

There is a critical point when initializing the value on the declaration line will get an error when trying compiler with c++98.

#include <vector>
#include <iostream>

int main(void)
{
    std::vector<int> v = {1, 2, 3, 4, 5};

    for (int i = 0; i < v.size(); i++)
    {
        std::cout << v[i] << std::endl;
    }
    return 0;
}

To compile I use g++ -std=98 main.cpp

main.cpp:6:22: error: in C++98 ‘v’ must be initialized by constructor, not by ‘{...}’
    6 |     std::vector<int> v = {1, 2, 3, 4, 5};
      |                      ^
main.cpp:6:40: error: could not convert ‘{1, 2, 3, 4, 5}’ from ‘<brace-enclosed initializer list>’ to ‘std::vector<int>’
    6 |     std::vector<int> v = {1, 2, 3, 4, 5};
      |                                        ^
      |                                        |
      |                                        <brace-enclosed initializer list>

<aside> ⚠️ If compiled with -std=c++11 ****will work with you without error. The reason for that's c++98 doesn’t support the initial list with vector.

</aside>

Access Elements

Returns a reference to the element at position n in the vector container.

Untitled

<aside> 🚫 Don’t initiate value by using a list, it will not compile with c++98.

</aside>

Size & Capacity.

The size of the currently allocated storage capacity in the vector is measured in terms of the number of elements it can hold.

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some content in the vector:
  for (int i=0; i<100; i++) myvector.push_back(i);

  std::cout << "size: " << (int) myvector.size() << '\\n';
  std::cout << "capacity: " << (int) myvector.capacity() << '\\n';
  std::cout << "max_size: " << (int) myvector.max_size() << '\\n';
  return 0;
}
size: 100
capacity: 128
max_size: 1073741823

Untitled