函数调用中的c ++ 11向量初始化 [英] c++11 vector initialization in a function call

查看:55
本文介绍了函数调用中的c ++ 11向量初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在c ++ 11中定义向量的新快捷方式有疑问.假设我有以下课程

I have a question about the new shortcut way of defining vectors in c++11. Suppose I have the following class

struct Tester{

  vector< vector<int> > data;

  Tester(){
    data = vector< vector<int> >();
  }

  void add(vector<int> datum){
    data.push_back(datum);
  }

};

然后,以下将按预期工作:

Then, the following works as expected:

int main(){
    Tester test = Tester();
    vector<int> datum = vector<int>{1,2,3};
    test.add(datum);
}

但这不是:

int main(){
    Tester test = Tester();
    test.add(vector<int>{1,2,3});
}

有人可以向我解释区别吗?我该如何在第二个main()中尝试快捷方式?

Can someone please explain the difference to me? How can I do the shortcut I attempt in the second main()?

推荐答案

您的代码似乎还可以,但是您使用的编译器却不行(看上去很旧).

Your code seems to be okay but the compiler you're using is not (which seems to be old).

顺便说一句,你做得太多了.

By the way, you're doing too much.

这应该足够了:

vector<int> datum{1,2,3}; //initialization

test.add({1,2,3}); //create vector<int> on the fly and pass it to add()

别忘了更新您的编译器.

Don't forget to update your compiler.

此外,行 data = vector<向量< int>>(); 也太多了.不需要.向量是自动构造的,这意味着您可以将类的构造函数保留为空,或者根本不使用它,因为它仍然无能为力.

Also, the line data = vector< vector<int> >(); is also too much. It is not needed. The vector is constructed automatically, which means you can leave the constructor of your class empty, or don't have it at all, as it doesn't do anything anyway.

这篇关于函数调用中的c ++ 11向量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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