gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:47:57 25 4
gpt4 key购买 nike

编辑

*请为这个话题点赞,因为我不能再在这个论坛上提问了。编程是我的生命,我只是因为自动禁止而陷入困境。谢谢(或者我需要版主的帮助来解决这个问题*

我是 C++ 的初级程序员,我想基本上返回一个 std::vector当我调试我的代码时,我得到 function call missing argument list 。这是我的简单代码

谢谢你的帮助

#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();

如果没有括号,则为语法错误。

顺便说一下,您可以做的另一件事来简化您的代码是像这样声明 vector :

std::vector<int> a;

或者在 C++11 中

std::vector<int> a{};

这两者都将默认构造 vector ——这适用于任何类类型。

这样做,

std::vector<int> a = std::vector<int>();

不是那么好,因为它更长并且让你输入两次,而且它复制初始化它而不是默认构造它,这略有不同并且可能效率较低。

关于c++ - 在 C++ 中返回一个 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34756169/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com