Return pointer to a vector of objects as a function return

I hope I can explain what I need to do, that is how lost I am.
Let's say you have a simple class User. For this purpose let's say really simple class.
What I am trying to do is to return a vector pointer from a function that points to a vector of Users.
I am trying to return this vector pointer in main function to a vector pointer or what that is necessary.
I have create the vector on the go. Let's say I only want to create User vector based on gender. So this will be
determined while the program is running. All the data is saved to a text file. I am reading from the file. Only get those users
who are female or male.

For this purpose, let's assume that the class is like the one below
1
2
3
4
5
6
7
8
9
10
11
12
Class User
	private:
		name;
		age;
		gender;
	public:
		getName;	
		setName;
		getAge;
		setAge;
		getGender;
		setGender;

Ask user for the input (Male or female)
call function findMatches
starts reading from the file
looks at gender info then creates vector of objects, also sets the name and age for each match with the help of pointer
and returns the pointer to the vector of objects to a receiver in main function.
Back in main the data type receives this vector pointer by a necessary data type. Not sure what this would be.


Any suggestions on how to do this.
1
2
3
4
5
vector<Users>* function()
{
  vector<Users>* pointer = new vector<Users>;
  return pointer;
}
> What I am trying to do is to return a vector pointer from a function that points to a vector of Users.

Use value semantics:

1
2
3
4
5
6
7
8
9
std::vector<User> find_matches( /* ... */ )
{
    std::vector<User> result ; // initially empty
    
    // open and read the file
    // add matching User objects to the vector 

    return result ; 
}


And in main(): const std::vector<User> matching_users = find_matches( /* ... */ ) ;
Use value semantics:
JLBorges, thanks for the suggestion. I will do it from now on. Are there any guidelines for value semantics?
Thanks.
1
2
3
4
vector<Users>* function()
{
  vector<Users>* pointer = new vector<Users>;
  return pointer;
}


Does this pointer can use the class methods?
pointer->setAge()
pointer->setName();
Last edited on
> Are there any guidelines for value semantics?

In general, return an object by value.
Also see:
https://en.wikipedia.org/wiki/Return_value_optimization
http://en.cppreference.com/w/cpp/language/copy_elision

For passing parameters to functions:
For "in" parameters, pass cheaply-copied types by value and others by reference to const.
For "in-out" parameters, pass by reference to non-const.
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-in
Alright, finally I got this but I am using vector<Class*> structure rather than vector<Class>* structure.

I have checked the address of the vectors and everything works.
Thanks for your help.
Topic archived. No new replies allowed.