Chr*_*way 26 c++ vector literals
我正在编写一些针对C++ API的代码,它采用向量向量的向量,并且编写如下代码的代码变得乏味:
vector<string> vs1;
vs1.push_back("x");
vs1.push_back("y");
...
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1.push_back(vs1);
vvs1.push_back(vs2);
...
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs.push_back(vvs1);
vvvs.push_back(vvs2);
...
Run Code Online (Sandbox Code Playgroud)
C++是否有矢量文字语法?即,类似于:
vector<vector<vector<string>>> vvvs =
{ { {"x","y", ... }, ... }, ... }
Run Code Online (Sandbox Code Playgroud)
有没有非内置的方法来实现这一目标?
小智 39
vector<vector<vector<string> > > vvvs =
{ { {"x","y", ... }, ... }, ... };
Run Code Online (Sandbox Code Playgroud)
但是在今天的C++中,你只能使用boost.assign来实现:
vector<string> vs1;
vs1 += "x", "y", ...;
vector<string> vs2;
...
vector<vector<string> > vvs1;
vvs1 += vs1, vs2, ...;
vector<vector<string> > vvs2;
...
vector<vector<vector<string> > > vvvs;
vvvs += vvs1, vvs2, ...;
Run Code Online (Sandbox Code Playgroud)
...或使用Qt的容器,让你一次性完成:
QVector<QVector<QVector<string> > > vvvs =
QVector<QVector<QVector<string> > >() << (
QVector<QVector<string> >() << (
QVector<string>() << "x", "y", ...) <<
... ) <<
...
;
Run Code Online (Sandbox Code Playgroud)
另一个半合理选项,至少对于平面向量,是从数组构造:
string a[] = { "x", "y", "z" };
vector<string> vec(a, a + 3);
Run Code Online (Sandbox Code Playgroud)