- C++17 STL Cookbook
- Jacek Galowicz
- 290字
- 2025-04-04 19:00:06
How to do it...
Applying a structured binding in order to assign multiple variables from one bundled structure is always one step. Let's first see how it was done before C++17. Then, we can have a look at multiple examples that show how we can do it in C++17:
- Accessing individual values of an std::pair: Imagine we have a mathematical function, divide_remainder, which accepts a dividend and a divisor parameter and returns the fraction of both as well as the remainder. It returns those values using an std::pair bundle:
std::pair<int, int> divide_remainder(int dividend, int divisor);
Consider the following way of accessing the individual values of the resulting pair:
const auto result (divide_remainder(16, 3));
std::cout << "16 / 3 is "
<< result.first << " with a remainder of "
<< result.second << '\n';
Instead of doing it as shown in the preceding code snippet, we can now assign the individual values to individual variables with expressive names, which is much better to read:
auto [fraction, remainder] = divide_remainder(16, 3);
std::cout << "16 / 3 is "
<< fraction << " with a remainder of "
<< remainder << '\n';
- Structured bindings also work with std::tuple: Let's take the following example function, which gets us online stock information:
std::tuple<std::string,
std::chrono::system_clock::time_point, unsigned>
stock_info(const std::string &name);
Assigning its result to individual variables looks just like in the example before:
const auto [name, valid_time, price] = stock_info("INTC");
- Structured bindings also work with custom structures: Let's assume a structure like the following:
struct employee {
unsigned id;
std::string name;
std::string role;
unsigned salary;
};
Now, we can access these members using structured bindings. We can even do that in a loop, assuming we have a whole vector of those:
int main()
{
std::vector<employee> employees {
/* Initialized from somewhere */};
for (const auto &[id, name, role, salary] : employees) {
std::cout << "Name: " << name
<< "Role: " << role
<< "Salary: " << salary << '\n';
}
}