0

我想按如下方式初始化这个vector-of-vector-of-strings,用g++ 4.4.7编译(由于操作策略,我不能使用更新的版本。

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

用 编译g++ -std=gnu++0x,失败如下:

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 ...]

这个问题表明我的语法是正确的,但 g++ 4.4 没有正确或完全支持我正在尝试做的事情。

完成这个向量的向量初始化的简单后备方法是什么?

4

2 回答 2

2

这是一个黑客,但这里有

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);
  }
}

要查看它的实际效果,请转到此处

于 2013-09-12T23:18:38.923 回答
0

感谢 @Dyp 提出这个 Boost 解决方案:

#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") );
于 2013-09-13T00:06:35.983 回答