在c ++中返回一个std :: vector

sac*_*amm 0 c++ vector return-value c++11

编辑

*请提出这个主题,因为我在这个论坛上不能再提问了.编程就是我的生活,我因为自动禁止而陷入困境.谢谢(或者我需要主持人的帮助来解决这个问题*

我是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;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*eck 9

std::vector大小为一个成员函数,而不是一个成员变量.你这样使用它:

int size = a.size();
Run Code Online (Sandbox Code Playgroud)

如果没有括号,则表示语法错误.

顺便提一下,你可以做的另一件事就是简化你的代码:声明这样的向量:

std::vector<int> a;
Run Code Online (Sandbox Code Playgroud)

或者在C++ 11中

std::vector<int> a{};
Run Code Online (Sandbox Code Playgroud)

这两个都将默认构造向量 - 这适用于任何类类型.

这样做,

std::vector<int> a = std::vector<int>();
Run Code Online (Sandbox Code Playgroud)

不是很好,因为它更长,让你输入两次,并且它复制初始化它而不是默认构造它,这稍微不同,可能效率较低.

  • @sachaamm请问每个问题一个问题,评论是批评或要求澄清.我会告诉你发一个新问题,但你之前在这个网站上已经回答了你的问题.使用搜索功能. (4认同)