我想初始化这个字符串向量,用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 不能正确或完全支持我正在尝试做的事情。
完成这种向量到向量初始化的简单回退方法是什么?
这是一个黑客,但这里是
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);
}
}
要查看它的实际效果,请转到此处。
感谢@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") );