C++ Vectors

πŸ“¦ C++ Vectors

std::vector is a dynamic array provided by the C++ Standard Template Library (STL).
It can grow or shrink at runtime and offers fast random access, making it one of the most commonly used containers in C++.


πŸ”Ή 1. Why Use vector?

  • Dynamic size (unlike arrays)

  • Contiguous memory (fast access)

  • Automatic memory management

  • Rich set of member functions

  • Works seamlessly with STL algorithms


πŸ”Ή 2. Include Header

#include <vector>

πŸ”Ή 3. Declaring a Vector

std::vector<int> v;

With initialization:

std::vector<int> v = {1, 2, 3, 4};

With size:

std::vector<int> v(5); // size 5, default values
std::vector<int> v(5, 10); // size 5, all values 10

πŸ”Ή 4. Adding Elements

v.push_back(10);
v.push_back(20);

πŸ”Ή 5. Accessing Elements

cout << v[0]; // no bounds checking
cout << v.at(0); // bounds-checked
cout << v.front(); // first element
cout << v.back(); // last element

πŸ”Ή 6. Traversing a Vector

Using Index

for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}

Using Range-based Loop

for (int x : v) {
cout << x << " ";
}

Using Iterator

for (auto it = v.begin(); it != v.end(); ++it) {
cout << *it << " ";
}

πŸ”Ή 7. Removing Elements

v.pop_back(); // removes last element
v.erase(v.begin()); // removes first element
v.erase(v.begin() + 1); // removes element at index 1

πŸ”Ή 8. Size vs Capacity

cout << v.size(); // number of elements
cout << v.capacity(); // allocated memory

Reserve capacity:

v.reserve(100);

πŸ”Ή 9. Insert Elements

v.insert(v.begin() + 1, 50);

Insert multiple:

v.insert(v.begin(), 3, 7); // insert 3 times 7

πŸ”Ή 10. Clear a Vector

v.clear(); // removes all elements
v.empty(); // checks if vector is empty

πŸ”Ή 11. Sorting a Vector

#include <algorithm>
sort(v.begin(), v.end());

Descending:

sort(v.begin(), v.end(), greater<int>());

πŸ”Ή 12. Vector of Objects

class Student {
public:
int id;
};

vector<Student> students;
students.push_back({101});


πŸ”Ή 13. 2D Vector

vector<vector<int>> matrix(3, vector<int>(4, 0));

πŸ”Ή 14. Time Complexity

OperationComplexity
AccessO(1)
push_backO(1) amortized
insert/erase (middle)O(n)
pop_backO(1)

❌ Common Mistakes

v[5] = 10; // ❌ out of bounds

βœ” Use at() if unsure.


πŸ“Œ Summary

  • vector is a dynamic array

  • Fast access, flexible size

  • Use push_back() to add

  • Use erase() to remove

  • size() vs capacity() matters

  • Core STL container

You may also like...