waqqasfarooq.com

  • Increase font size
  • Default font size
  • Decrease font size
Home Useful Code Snippets Remove elements from std::vector and std::list


Remove elements from std::vector and std::list

E-mail Print PDF
User Rating: / 8
PoorBest 

Often times you would want to filter out some data from your collection of a vector or a list. The following code snippet shows a quick and fool proof way of doing that:

Remove elements from vector or list

View source
  1.     // Defining our collection type. We can interchange the following line
  2. // with std::list and the output will be the same.
  3. typedef std::vector < int > ScalarCollection;
  4.  
  5. // Create and populate the collection
  6. int myints[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
  7. ScalarCollection collection(myints, myints + sizeof(myints) / sizeof(int));
  8.  
  9. // Print all elements in the collection
  10. // Result: 1 2 3 4 5 6 7 8 9
  11. for (ScalarCollection::const_iterator it = collection.begin(); it != collection.end(); ++it)
  12. std::cerr << *it << " ";
  13. std::cerr << std::endl;
  14.  
  15. // erase(from, till)
  16. // from: last element after applying isOdd -
  17. // till: end of the collection
  18.  
  19. // The following combination of 'erase' and 'remove_if' will
  20. // 1. remove elements that pass the criteria: isOdd
  21. // 2. shrink the size of the collection based on the number of elements removed
  22. collection.erase(
  23. std::remove_if(collection.begin(), collection.end(), isOdd),
  24. collection.end()
  25. );
  26.  
  27. // Print all elements in the collection
  28. // Result: 2 4 6 8
  29. for (ScalarCollection::const_iterator it = collection.begin(); it != collection.end(); ++it)
  30. std::cerr << *it << " ";
  31. std::cerr << std::endl;
  32.  
  33.  
  34. /**
  35.  * Checks to see if the input is an odd integer
  36.  */
  37. bool isOdd (int input)
  38. {
  39. return ((input % 2) == 1);
  40. }