Sort std::vector but ignore a certain number

前端 未结 6 620
我寻月下人不归
我寻月下人不归 2021-01-28 12:05

I have an std::vector of the size 10 and each entry is initially -1. This vector represents a leaderboard for my game (high scores), and -1 just means th

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 12:08

    An alternative approach is to use reserve() instead of resize().

    std::vector myVector;
    myVector.reserve(10);
    
    for each line in file:
      int number_in_line = ...;
      myVector.push_back(number_in_line);
    
    std::sort(myVector.begin(), myVector.end());
    

    This way, the vector would have only the numbers that are actually in file, no extra (spurious) values (e.g. -1). If the vector need to be later passed to other module or function for further processing, they do not need to know about the special nature of '-1' values.

提交回复
热议问题