fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. int main()
  6. {
  7. std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
  8. // get the position of -1
  9. auto itr = std::find(test.begin(), test.end(), -1);
  10. // sort all elements so that -1 will be moved to end of vector
  11. std::sort(test.begin(), test.end(), [](const int& lhs, const int& rhs )
  12. {
  13. if( lhs == -1 ) return false;
  14. if( rhs == -1 ) return true;
  15. return lhs < rhs;
  16. });
  17.  
  18. test.erase(test.end()-1); // now erase it from end
  19. test.insert(itr, -1); // add to the erlier position
  20.  
  21. for(const auto& it: test)
  22. std::cout << it << " ";
  23.  
  24. return 0;
  25. }
  26.  
  27.  
Success #stdin #stdout 0s 4528KB
stdin
Standard input is empty
stdout
1 3 4 5 -1 6 8 9 11