fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <cctype>
  5. #include <algorithm>
  6.  
  7. int main()
  8. {
  9. std::vector<std::string> Vec{ "A", "B", " ", "D", "E", " ", "", " " };
  10.  
  11. // Helper function to see if string is all whitespace
  12. // Can also be implemented as free-function for readablity and
  13. // reusability of course
  14. auto stringIsWhitespace = [](const auto &str)
  15. {
  16. return std::all_of(
  17. begin(str), end(str), [](unsigned char c) { return std::isspace(c); });
  18. };
  19.  
  20. // Find first non-whitespace from the back
  21. auto it = std::find_if(rbegin(Vec), rend(Vec), stringIsWhitespace);
  22. // Erase from there to the end
  23. Vec.erase(it.base(), end(Vec));
  24.  
  25.  
  26. for (auto const &str : Vec)
  27. {
  28. std::cout << "Element: " << str << std::endl;
  29. }
  30.  
  31. return 0;
  32. }
Success #stdin #stdout 0s 4224KB
stdin
Standard input is empty
stdout
Element: A
Element: B
Element:  
Element: D
Element: E
Element:  
Element: 
Element: