-->

C++ - Vectors Part 5: Advanced Vector Features

Advanced features like sorting, swapping, and multidimensional vectors make vectors versatile.

Examples and Explanation

Sorting a Vector

#include <algorithm>

std::sort(vec.begin(), vec.end());

Explanation: The std::sort() function sorts the vector in ascending order.

Swapping Two Vectors

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

std::vector<int> vec2 = {4, 5, 6};

vec1.swap(vec2);

Explanation: The swap() method exchanges the contents of two vectors.

Multidimensional Vectors

std::vector<std::vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}};

std::cout << matrix[0][1]; // Output: 2

Explanation: Vectors can represent 2D arrays, ideal for matrix operations or grids.

Custom Objects in Vectors

struct Point {

    int x, y;

};

std::vector<Point> points = {{1, 2}, {3, 4}};

points.emplace_back(5, 6);

Explanation: Vectors can store complex data types like structs or objects.