I am trying to do some work with my class and std::vector. I encountered with folloing problem,=
Here is my code:
class A
{
private:
........
public:
vector<int>* ret_vec();
};
vector<int>* A::ret_vec()
{
vector<int> vec; // vec is declared as a local variable
......
return &vec;
}
int main()
{
.....
vector<int>* vec = A.ret_vec(); // size of vec is 0 !!!
}
As you can see in the code, vec
in vector<int>* A::ret_vec()
is declared as a local variable, and when I assgin it to a pointer in main
, the size of vec
is 0.
Thus, I used following method instead:
class A
{
private:
vector<int> vec; // vec is declared as a member variable
public:
vector<int>* ret_vec();
};
vector<int>* A::ret_vec()
{
......
return &vec;
}
int main()
{
.....
vector<int>* vec = A.ret_vec(); // size of vec is ok
}
Now, as I declare vec
as a member variable, when I assign it to a local pointer in main
, its size is exactly as I expected.
May I know why is this? Many thanks.
========================================================== EDIT:
I'm sorry i haven't explained myself clear at the first place. I am dealing with a large data set vec
, and the time performance is my current priority. Thus I'm afraid that return vector by values is not an option.