C++:C++ std::set and std::pair / std::tuple Explained
C++•Sets & Tuples

C++ std::set and std::pair / std::tuple Explained

Explore std::set for unique sorted collections, and std::pair / std::tuple for returning multiple values from functions.

Syntax

#include <set> #include <tuple> std::set<int> uniqueVals; auto t = std::make_tuple(1, "A", true);

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
std::setContainerStores unique elements sorted automatically.
std::tupleHeterogeneous ContainerFixed-size collection of heterogeneous types.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C++ locally:

#include <iostream>
#include <set>
#include <tuple>
#include <string>

// Function returning multiple values via tuple
std::tuple<std::string, int, double> getSystemStatus() {
    return {"Worker-01", 8080, 99.4};
}

int main() {
    // 1. std::set: Automatic deduplication and sorting
    std::set<int> uniquePortCodes = {80, 443, 8080, 80, 22, 443};
    std::cout << "Unique Sorted Ports:\n";
    for (int port : uniquePortCodes) {
        std::cout << "  Port: " << port << "\n";
    }

    // 2. Unpacking tuple using C++17 structured binding
    auto [name, port, uptime] = getSystemStatus();
    std::cout << "\nNode Status: " << name << " on port " << port << " (Uptime: " << uptime << "%)\n";

    return 0;
}
Expected Output:
Unique Sorted Ports:
  Port: 22
  Port: 80
  Port: 443
  Port: 8080

Node Status: Worker-01 on port 8080 (Uptime: 99.4%)

How It Works: Step-by-Step

  • Lines 7-9: Defines function returning std::tuple of string, int, double.
  • Line 13: std::set deduplicates input values 80 and 443 and sorts in ascending order.
  • Line 20: C++17 structured binding unpacks tuple fields into distinct variables.

Key Concepts

  • std::set prevents duplicate entries and sorts elements with O(log n) operations.
  • std::unordered_set provides O(1) hash table set storage.
  • C++17 structured bindings make tuples ergonomic and readable.

Common Mistake: Trying to access tuple elements with runtime variables

std::get<N>(t) requires N to be a compile-time constant integer.

❌ Incorrect
int i = 0;
std::get<i>(myTuple); // Compile Error! i must be constexpr
✅ Correct
std::get<0>(myTuple); // Compile-time index

Related C++ Tutorials & Compiler

Run and test C++ on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C++ Online Compiler