-2

I have a c++ vector of student objects with each object having an ID(string), name (string) and age(int).

std::vector<student> myVector;

Lets say the vector looks like this

[{"1", "Tom", 12}, {"2", "David", 10}, {"3", "Adam", 15}, {"4", "Jill", 20}]

Is there any way I can delete an object in the vector using the student Name like:

myVector.deleteObjectWithName(David)

such that my remaining vector is now

[{"1", "Tom", 12}, {"3", "Adam", 15}, {"4", "Jill", 20}]

CompuChip
  • 9,143
  • 4
  • 24
  • 48
  • 2
    `std::remove_if` is what you need – DimChtz Jul 27 '16 at 14:30
  • This isn't the same question which you marked: that asked about value, while this requires `remove_if` – Dutow Jul 27 '16 at 14:32
  • Of course, as you asked the question, `std::remove_if` is the answer as pointed out by @DimChtz. But I can imagine that in general you want to look up students by ID, in which case an `std::map` might be a more useful data structure. (Also, why is student ID a string?) {edit} nvm, see you want to delete by name instead of ID. General remarks might still be useful though. – CompuChip Jul 27 '16 at 14:32
  • I have edited the question. I want to delete by name. Student ID is a string because I do not plan to do any arithmetic on it – liphoto liphoto Jul 27 '16 at 14:42
  • But if it is a unique number, making it a numeric datatype still has some advantages, such as the fact that you can quickly compare it to other IDs and can safely use it as keys into an `std::map`. Agree with the fact that the duplicate is not a duplicate btw. – CompuChip Jul 27 '16 at 14:44

1 Answers1

1

std::remove_if is what you need:

myVector.erase(std::remove_if(myVector.begin(), myVector.end(), 
  [](students const& s) { return s.name == "David"; }), myVector.end());
CompuChip
  • 9,143
  • 4
  • 24
  • 48
Dutow
  • 5,638
  • 1
  • 30
  • 40
  • I formatted the output a little bit, and I think there was a missing bracket. Please check if it is correct. – CompuChip Jul 27 '16 at 14:36
  • It is, I missed that bracket, and forgot to recheck it after I noticed that the question was closed – Dutow Jul 27 '16 at 14:37