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.

Recommended Answers

All 4 Replies

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.

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

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

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... :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.