wispymisty
wispymisty

Reputation: 129

Structured binding not working in C++17

I have tried out the following code snippet from Expert C++ Programming. g++ is giving compilation error. Is it simply a case of g++ not catching up to the C++17 syntax?

lib_test.cpp:39:15: error: expected unqualified-id before ‘[’ token
          auto [iter, success] = m.try_emplace(b.country, b, 1);
               ^

I use -std=c++17 flag.

g++ (Ubuntu 6.4.0-17ubuntu1) 6.4.0 20180424

#include <iostream>
#include <functional>
#include <list>
#include <map>

using namespace std;


struct billionaire {
  string  name;
  double  dollars;
  string  country;
};  


void efficient_map_test()
{
   list<billionaire> billionares {
           {"Bill Gates", 86.0, "USA"},
           {"Warren Buffet", 75.6, "USA"},
           {"Jeff Bezos", 72.8, "USA"},
           {"Amnancio Ortega", 71.3, "Spain"},
           {"Mark Zuckerberg", 56.0, "USA"},
           {"Carlos Slim", 54.5, "Mexico"},

           {"Bernard Arnualt", 41.5, "France"},
           {"Liliane Bettencourt", 39.5, "France"},
           {"Wang Jianlin", 31.3, "China"},
           {"Li Ka-shing", 31.2, "Hong Kong"}
   };      

   map<string, pair<const billionaire, size_t>> m;

   for (const auto &b: billionares) {
      auto [iter, success] = m.try_emplace(b.country, b, 1);
      if (!success) {
           iter->second.second += 1;
        }    
   }    


 for (const auto &[key, value]: m) {
        const auto &[b, count ] = value;
        cout << b.country << " : " << count
                                   << "billionaires. Richest is "
                                   << b.name << " with " << b.dollars
             << " B$n";            
   }         
}  

int main()
{
     return 0;
}  

Edit: 1. -std=C++17 -> -std=c++17
2. Added empty main to make it copy/paste ready

Upvotes: 3

Views: 3807

Answers (2)

frido
frido

Reputation: 818

It's due to a lack of support in gcc (version 6.3, 6.4, ...).

Even though you can use c++17 with these versions, this particular feature is missing.

This small example can be compiled on Debian Buster g++ (Debian 8.3.0-6) 8.3.0 without error, however fails on Debian Strech g++ (Debian 6.3.0-18+deb9u1) 6.3.0.

#include <tuple>

int main() {
  auto a = std::make_tuple(0, true);
  auto [b, c] = a;
  return 0;
}
# g++ -std=c++17 -o main main.cc 
main.cc: In function 'int main()':
main.cc:5:8: error: expected unqualified-id before '[' token
   auto [b, c] = a;
        ^

Upvotes: 0

OrenIshShalom
OrenIshShalom

Reputation: 7172

You simply have the compilation flag wrong. it's a lower case c:

g++ -std=c++17 -o main main.cpp

And not capital C like you wrote in the question (-std=C++17). Oh and please add an empty main function so that your code is copy-paste ready.

Upvotes: 2

Related Questions