Sign in to follow this  
loachman

Vector Troubles

Recommended Posts

loachman    121
Hello. I have a function where I have user input a number. I then use that number with the vect.push_back(number). I am also returning the number from that function. Back in main though I ran vect.size() and the vector showed as 0. Also ran vect.empty() and it shows indeed that that the vector is empty.

//vector delcaration
vector<int> numbers;
//function
int get_number(vector<int> vect){
	int number;
	
	cout << "Please enter a number ";
         cin >> number;
	vect.push_back(number);
	return number;//returning for another part of program
    
	
}
// thats the function

But back in main the vector I pass in as an arg is empty after running that fucntion several times. Thanks

Share this post


Link to post
Share on other sites
Crypter    748
You should pass the vector as a refrence:

int get_number(vector<int>& vect){
int number;

cout << "Please enter a number ";
cin >> number;
vect.push_back(number);
return number;//returning for another part of program


}

Share this post


Link to post
Share on other sites
CrimsonSun    336
When you pass an object (in this case a vector) by value to a function, the function makes a copy of that object to work with. Therefore any changes made to the passed object inside the function will have no persistent changes on the object passed once the function goes out of scope. To modify the object, pass it by reference or pass a pointer to the object.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this