[英]return a std::vector in c++
编辑
*请支持这个话题,因为我不能在这个论坛上再问任何问题了。 编程是我的生命,我只是因为自动禁止而陷入困境。 谢谢您(或者我需要主持人的帮助才能解决此问题*
我是C ++的初学者,我想基本上返回一个std::vector
调试代码时,我得到函数调用缺少参数列表。 这是我的简单代码
谢谢你的帮助
#include "stdafx.h"
#include <vector>
#include <iostream>
static std::vector<int> returnStaticVector();
static std::vector<int> returnStaticVector(){
std::vector<int> vectorInt = std::vector<int>();
vectorInt.push_back(0);
return vectorInt;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> a = std::vector<int>();
a = returnStaticVector(); // Compile , but error when I try to access to the size of the std::vector
//int size = a.size; //error C3867: 'std::vector<int,std::allocator<_Ty>>::size': function call missing argument list; use '&std::vector<int,std::allocator<_Ty>>::size' to create a pointer to member
//int size = &a.size; // & Illegal operation
//int& size = a.size; //error C3867: 'std::vector<int,std::allocator<_Ty>>::size': function call missing argument list; use '&std::vector<int,std::allocator<_Ty>>::size' to create a pointer to member
int* size = a.size; //error C3867: 'std::vector<int,std::allocator<_Ty>>::size': function call missing argument list; use '&std::vector<int,std::allocator<_Ty>>::size' to create a pointer to member
return 0;
}
在std::vector
size是成员函数,而不是成员变量。 您可以这样使用它:
int size = a.size();
如果没有括号,则为语法错误。
顺便说一句,您可以简化代码的另一件事是声明向量,如下所示:
std::vector<int> a;
或在C ++ 11中
std::vector<int> a{};
这两个都将默认构造向量-这适用于任何类类型。
这样做
std::vector<int> a = std::vector<int>();
之所以不好,是因为它更长,并且使您两次键入内容,并且它会复制它来初始化它,而不是默认构造它,这略有不同并且可能会降低效率。
首先,第一件事-代码中真正的编译问题是因为您使用了a.size而不是a.size() 。 尝试更改它,代码应成功编译。
除此之外,我不认为返回像您所做的那样的向量不是一个好主意。 尝试使用调用函数的引用传递矢量。 那是更好的设计。
如果您仍在考虑按值返回,请考虑“复制省略”,它是编译器实现的一种优化,可以在许多情况下防止不必要的复制。 在许多情况下,它使按值返回或按值传递成为可能。
在此处阅读有关复制省略的更多信息:-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.