简体   繁体   中英

Alternative to brace initialization in g++ 4.4

I want to initialize this vector-of-vector-of-strings as follows, compiling with g++ 4.4.7 ( due to Operations policy, I can't use a more recent version. )

vector<vector<string>> phs2tm_vec {
    { "manager_n",  "manager_a",  "manager_e", "manager_p" },
    { "manager_na", "manager_ne", "manager_np" },
    { "manager_ccx" },
    { "manager_icx" }
};

Compiling with g++ -std=gnu++0x , it fails as follows:

error: no matching function for call to 'std::vector<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, std::allocator<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > > >::vector(<brace-enclosed initializer list>)'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:271: note: candidates are: std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const _Alloc&) [with _Tp = std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >, _Alloc = std::allocator<std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >]

[additional candidates not listed ...]

This question suggests that my syntax is correct but that g++ 4.4 doesn't correctly or fully support what I'm trying to do.

What would be a simple fall-back method to accomplish this vector-of-vector initialization?

It's a hack, but here goes

vector<vector<string> > phs2tm_vec;

{
  const char *data[4][4] = {
    { "manager_n",  "manager_a",  "manager_e", "manager_p" },
    { "manager_na", "manager_ne", "manager_np" },
    { "manager_ccx" },
    { "manager_icx" }
  };

  for(size_t i=0; i<sizeof(data)/sizeof(data[0]); ++i) {
    vector<string> row;
    for(size_t j=0; j<sizeof(data[0])/sizeof(data[0][0]); ++j) {
      if(!data[i][j]) break;      // end of row
      row.push_back(data[i][j]);
    }
    phs2tm_vec.push_back(row);
  }
}

To see it in action, go here .

Thanks to @Dyp for suggesting this Boost solution:

#include <boost/assign/list_of.hpp>
using boost::assign::list_of;

vector< vector< string >> phs2tm_vec =
    list_of< vector< string >>
    ( list_of ("manager_n")   ("manager_a")   ("manager_e")  ("manager_p") )
    ( list_of ("manager_na")  ("manager_ne")  ("manager_np") )
    ( list_of ("manager_ccx") )
    ( list_of ("manager_icx") );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM