C++ 向量文字,或类似的东西
我正在针对 C++ API 编写一些代码,该 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);
...
C++ 有向量文字语法吗? 即,类似:
vector<vector<vector<string>>> vvvs =
{ { {"x","y", ... }, ... }, ... }
是否有非内置方法可以实现此目的?
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);
...
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C++0x 中,您将能够使用您想要的语法:
但在今天的 C++ 中,您只能使用 boost.assign 可以让您执行以下操作:
...或使用 Qt 的容器 让你一次性完成:
另一个半理智的选项,至少对于平面向量,是从数组构造:
In C++0x you will be able to use your desired syntax:
But in today's C++ you are limited to using boost.assign which lets you do:
... or using Qt's containers which let you do it in one go:
The other semi-sane option, at least for flat vectors, is to construct from an array:
基本上,没有内置语法可以做到这一点,因为 C++ 不知道向量以太; 它们只是来自便利的图书馆。
也就是说,如果您要加载复杂的数据结构,您应该从文件或类似的东西加载它; 否则代码太脆弱了。
Basically, there's no built-in syntax to do it, because C++ doesn't know about vectors ether; they're just from a convenient library.
That said, if you're loading up a complicated data structure, you should load it from a file or something similar anyway; the code is too brittle otherwise.