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:
| Parameter | Type | Description |
|---|---|---|
| std::set | Container | Stores unique elements sorted automatically. |
| std::tuple | Heterogeneous Container | Fixed-size collection of heterogeneous types. |
Ready-to-Run Code Example
Executable in CompilraRun 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
C++ std::vector (Dynamic Arrays): Methods and Memory
Master std::vector for dynamic contiguous arrays with push_back, emplace_back, and indexing.
C++ std::map and std::unordered_map (Hash Tables)
Learn associative key-value mapping with std::map (Red-Black tree) and std::unordered_map (Hash Table).
C++ std::string and std::string_view (C++17)
Master text manipulation with std::string and high-performance zero-copy std::string_view.
C++ Online Compiler
Open in Compilra IDE
Run and test C++ on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.