Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structured binding not working in C++17

Tags:

c++

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

like image 895
wispymisty Avatar asked May 19 '26 03:05

wispymisty


1 Answers

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.

like image 171
OrenIshShalom Avatar answered May 20 '26 18:05

OrenIshShalom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!