sachaamm sachaamm - 3 months ago 16
C++ Question

return a std::vector in c++

EDIT

*Please , upvote this topic because I cant ask anymore question in this forum.
Programming is my life and I'm just stuck because of an automated banning . Thank you ( or I need the help of a moderator to solve this problem *


I'm a beginner programmer in c++ and I want to basically return a

std::vector

When I debug my code I get function call missing argument list . Here is my simple code

Thanks for your help

#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;
}

Answer

In std::vector size is a member function, not a member variable. You use it like this:

int size = a.size();

If you don't have the parentheses, it is a syntax error.

Incidentally, another thing you can do to simplify your code is declare vectors like this:

std::vector<int> a;

Or in C++11

std::vector<int> a{};

Both of these will default-construct the vector -- this works for any class type.

Doing it this way,

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

is not as good because it is longer and makes you type things twice, and also it copy initializes it rather than default constructing it, which is slightly different and may be less efficient.

Comments