C++20 sections · 1024 units
Open in Course

Pairs in Vectors

Storing multiple pairs

You can store pairs in vectors to create collections of related value pairs. This is common for representing edges in graphs, coordinates, or any paired data. Declaration: vector<pair<int, int>> edges; To add elements: edges.push_back(make_pair(1, 2)); or edges.push_back({1, 2}); The brace syntax works in C++11 and later.

Access elements with indices: edges[0].first and edges[0].second. Iterate with range-based for: for (auto& e : edges) { cout << e.first << " " << e.second; } Vectors of pairs are common in competitive programming for storing graph edges, sorting by custom criteria, and grouping related values together.