Pair

Included in <utility> or <algorithm>. Used to store two values, of same type or not, in one variable.

pair<string, int> p = {"abc", 2};
// or: pair<string, int> p = make_pair("abc", 2);

p.first = "def";
p.second = 3;

Pairs can be used in data structures as well:

pair<int, int> a[100];     // array of pair
vector<pair<int, int>> v;  // vector of pair

To append to vector of pair:

v.push_back({"abc", 2});   // create pair and then append to vector
v.emplace_back("abc", 2);  // alternative: create pair in-place within the vector

Range-based for loop for vector of pair:

for (auto [f, s] : v) {
    cout << f << s << "\n";  // f: v[i].first, s: v[i].second
}

Custom Comparator for sort

sort accepts a third argument, which is a custom comparator function. The comparator function accepts two arguments, which will be elements from the array to be sorted. If the first argument should come before the second argument, return true, otherwise return false.

To sort an array of strings by their length ascending:

bool comp(string s, string t) {
    return s.length() < t.length();
}

int main() {
    int n = 4;
    string a[] = {"abc", "defgh", "ij", "lmnopq"};
    sort(a, a + 4, comp);
    for (int i = 0; i < n; i++) cout << a[i] << "\n";
}

Authored by s16f22