0

Specifically, specific elements. A project requires us to delete elements in a vector via course number. I assumed one would use an iterator, so that being said, would this work?

void student::drop_course(int d) {
	vector<int>::iterator f = find(c_id.begin(), c_id.end(), d);
	vector.erase(f);
	cout << "You have deleted course number " << d << endl;
}

Thanks in advanced.

3
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by Project_Panda
0

verify that the element is present first:

void student::drop_course(int d) 
{
  vector<int>::iterator f = find(c_id.begin(), c_id.end(), d);
  if( f != c_id.end() )
  {
    c_id.erase(f);
    cout << "You have deleted course number " << d << endl;
  }
}

if there are duplicate values in the vector, you need to put this in a loop.

0

Ah I see. Added it to my code. When I finish the other header I'll give it a whirl.

0

if you need to delete arbitrary elements a lot, then perhaps you don't want to use a vector, because it is very expensive, both to find it and to shift all the remaining elements

0

I agree and considered that, but our instructor wants us to use a container that she has taught in class, and being she's only taught array and vector... :(

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.