C++ vector 字面量,或类似的东西

标签 c++ vector literals

我正在针对 C++ API 编写一些代码,该 API 采用 vector 的 vector ,并且到处编写如下代码变得乏味:

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

C++ 有 vector 字面量语法吗?即,类似:

vector<vector<vector<string>>> vvvs = 
    { { {"x","y", ... }, ... }, ... }

有没有非内置的方法来完成这个?

最佳答案

C++0xwill be able使用您想要的语法:

vector<vector<vector<string> > > vvvs = 
    { { {"x","y", ... }, ... }, ... };

但在今天的 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, ...;

... 或使用 Qt's containers让您一口气完成:

QVector<QVector<QVector<string> > > vvvs =
    QVector<QVector<QVector<string> > >() << (
        QVector<QVector<string> >() << (
            QVector<string>() << "x", "y", ...) <<
            ... ) <<
        ...
    ;

另一个半理智的选择,至少对于平面 vector ,是从数组构造:

string a[] = { "x", "y", "z" };
vector<string> vec(a, a + 3);

关于C++ vector 字面量,或类似的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/758118/

相关文章:

c++ - C2679 二进制 '=' : no operator found which takes a right-hand operand of type 'point_t' (or there is no acceptable conversion)

在数组中查找三个数字的算法,使得 a< b < c 和 v[a]<v[c]<v[b]

C++11:防止将对象分配给引用

c++ - 我应该怎么做才能初始化结构数组

c++ - 在 vector 中推回后数字发生变化

ruby - 正则表达式中的 `\.` 和 `i` 是什么?

java - 如何理解java类字面量?

c++ - C++ 中两个字 rune 字的加法

c++ - 按顺序循环结果

c++ - 指针的类型