Vector Troubles

Started by
2 comments, last by CrimsonSun 16 years, 11 months ago
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
Advertisement
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    	}

Marvelous Thanks!
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.

This topic is closed to new replies.

Advertisement