Skip to main content
gamedev.net
🔒 Locked

remove ordered element from vector

Started by Edzio 4 replies 550+ views
Original Post
Edzio
Edzio
The following code is an attempt to remove a specific element from a vector of objects based an entered name where .dog_name is a class private member but knowing that I cannot access a private member method from outside the class definition, how would I pass the vector to the class or make this run as function called from main? (code does NOT compile yet) void depart_dog(vector<Dog>& d) { string name; cout << "which dog? " << endl; cin >> name; cout << name << " is going home. Bye!" << endl; cout << endl; for(int i = 0; i < d.size(); i++) if(name == d.dog_name) d.pop_back(); }
thallish
thallish
have a public class method return dog_name

class Dog{  string dog_name;public:  string getDogName(){return dog_name;)}

so it would be d.GetDogName() and if the names is equal, then remove the element at the i'th position.

I assume that vector<Dog> is defined in main().

regards
regards/thallishI don't care if I'm known, I'd rather people know me
Edzio
Edzio
thanks thallish that helped,
but the pop_back doesnt seem to know which element to pop
(the code DOES compile now)

void depart_dog(vector<Dog>& d)
{
string name;
cout << "which dog? " << endl;
cin >> name;
cout << name << " is going home. Bye!" << endl;
cout << endl;

for(int i = 0; i < d.size(); i++)
if(name == d.get_dog_name())
d.pop_back();

}
Edzio
Edzio
Dr Evil,

inside the vector<Dog> Yes, where Dog is a class
Captain P
Captain P
.pop_back() removes (and returns) the last element from the vector, in which case it's indeed useless to search for names... ;)

You should use .erase(i) instead.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.