mardi 29 juin 2021

is std::sort safe on this case [duplicate]

I've such a piece of code in my project:

vector<int> vec;
int begin = 0, end = 0;
for(...) {
    for (...) {
        if (x) {
            vec.push_back(some_value);
            end++;
        }
    }
    std::sort(vec.begin() + begin, vec.begin() + end, std::greater<int>());
    begin = end;
}

I'm trying to sort the vector vec piece by piece. But the bool x may be false. In this case, begin equals to end, so it may execute such a code: std::sort(vec.begin() + 3, vec.begin() + 3, std::greater<int>());

Is this safe even if vec.begin() + begin may not be able to be dereferenced? Or must I add a condition as below:

if (begin < end) {
    std::sort(vec.begin() + begin, vec.begin() + end, std::greater<int>());
}

Aucun commentaire:

Enregistrer un commentaire