C ++向量文字或类似的东西 [英] C++ vector literals, or something like them

查看:93
本文介绍了C ++向量文字或类似的东西的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在针对采用矢量向量的C ++ API编写一些代码,并且到处编写类似以下代码的代码变得很乏味:

I'm writing some code against a C++ API that takes vectors of vectors of vectors, and it's getting tedious to write code like the following all over the place:

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 ++是否具有矢量文字语法?即,类似于:

Does C++ have a vector literal syntax? I.e., something like:

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

是否有非内置的方式来完成此操作?

Is there a non-builtin way to accomplish this?

推荐答案

C ++ 0x 将能够使用所需的语法:

In C++0x you will be able to use your desired syntax:

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

但是在当今的C ++中,您只能使用 boost .assign ,您可以这样做:

But in today's C++ you are limited to using boost.assign which lets you do:

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的容器,您可以一次完成前往:

... or using Qt's containers which let you do it in one go:

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

至少对于平面向量而言,另一个半明智的选择是从数组构造:

The other semi-sane option, at least for flat vectors, is to construct from an array:

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

这篇关于C ++向量文字或类似的东西的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆