Table of Contents

<utility>

<utility> provides miscellaneous utilities: std::pair<T, U> (a two-element tuple), std::move (enable move semantics), std::forward (perfect forwarding), std::swap, and std::exchange.

std::pair is the building block for map key-value pairs, and std::move / std::forward are essential for writing efficient generic code.

Example

This example uses pair to store key-value data and demonstrates move semantics to avoid copying vectors.

// compile: g++ -std=c++11 -o utilityexample utilityexample.cpp
// run: ./utilityexample
// description: pair and move semantics
 
#include <utility>
#include <iostream>
#include <vector>
 
int main() {
    std::pair<int, std::string> p{42, "answer"};
    std::cout << "pair: " << p.first << ", " << p.second << "\n";
 
    std::vector<int> v1{1, 2, 3};
    std::vector<int> v2 = std::move(v1);
    std::cout << "moved vector size: " << v2.size() << ", v1 size: " << v1.size() << "\n";
 
    return 0;
}