0

Let's say we have a std::queue<std::pair<int, int> >.

To extract a pair, we can either do:

int r = q.front().first;
int c = q.front().second;

or

auto [rr, cc] = q.front();

where rr and cc can then be treated as regular int.

I've never encountered this type of syntax before. What does the standard say about it? What is the auto specifier extracting?

auto p = q.front();

would just be a regular std::pair.

  • 3
    Have a look for [Structured Binding](https://en.cppreference.com/w/cpp/language/structured_binding). – Scheff's Cat Jan 04 '23 at 07:16
  • This is explained in a [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and various SO posts. Refer to [how to ask](https://stackoverflow.com/help/how-to-ask) where the first step is to *"search and then research"*. – Jason Jan 04 '23 at 07:21
  • @user20896951 That is exactly what I did. I searched [what does syntax auto [a,b\] mean in c++](https://www.google.com/search?q=what+does+syntax+auto+[a%2Cb]+mean+in+c%2B%2B) on google and I found [post](https://stackoverflow.com/questions/70873747/in-this-syntax-what-is-the-actual-type-of-auto) on the first page explaining that it is called "structured bindings.". – Jason Jan 04 '23 at 07:36
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Jason Jan 04 '23 at 07:45

1 Answers1

2

It's a structured binding, which is available since C++17.

Further reading: https://en.cppreference.com/w/cpp/language/structured_binding

Another useful place for this would be, as an example, iterating over a map. The bound variables can be references by prepending with a &.

#include <map>
#include <iostream>

int main() {
    std::map<int, int> m { {1, 4}, {3, 7}, {4, 9} };

    for (auto &[k, v] : m) {
        std::cout << k << ": " << v << std::endl;
    }

    return 0;
}
Chris
  • 26,361
  • 5
  • 21
  • 42