Sort std::vector but ignore a certain number

前端 未结 6 628
我寻月下人不归
我寻月下人不归 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:32

    For the following, I assume that the -1 values are all placed at the end of the vector. If they are not, use KerrekSB's method, or make sure that you do not skip the indices in the vector for which no valid score is in the file (by using an extra index / iterator for writing to the vector).

    std::sort uses a pair of iterators. Simply provide the sub-range which contains non--1 values. You already know the end of this range after reading from a file. If you already use iterators to fill the vector, like in

    auto it = myVector.begin();
    while (...) {
        *it = stoi(...);
        ++it;
    }
    

    then simply use it instead of myVector.end():

    std::sort(myVector.begin(), it);
    

    Otherwise (i.e., when using indices to fill up the vector, let's say i is the number of values), use

    std::sort(myVector.begin(), myVector.begin() + i);
    

提交回复
热议问题