a; std::vector ...">

In C ++, is it safe to use std :: numeric_limits <double> :: max () as a special "flag"?

Considering

std::vector<double> a;
std::vector<int> ind;

where indis 1 sorted in ascending order.

I want to do the equivalent of the following:

for (auto it=ind.rbegin();it!=ind.rend();it++) a.erase(a.begin() + *it);

I came up with this:

for (auto it=ind.begin();it!=ind.end();it++) 
   a[*it] = std::numeric_limits<double>::max();
std::erase(std::remove(a.begin(),a.end(),std::numeric_limits<double>::max()),a.end());

This is very fast, but it makes no sense to use std :: numeric_limits :: max () as a flag in this context.

Of course, feelings should not influence the equation too much ... it is clear that comparing doubles in std :: remove is safe and the limit will never be put into practice in this vector in a working application, so it should be fine, no?

Any thoughts on this?


1 ) Ref comment OP . - alf

+3
1

"" , , , "":

std::vector<double> a;
std::vector<int> ind;

for (auto it = ind.rbegin(); it != ind.rend(); it++)
    a.erase(a.begin() + *it);

, , ind - a, , . a. , - .

, // a, , ind. erase() , . ( , a), :

size_t slow = 0; // where we are currently copying "to"
std::vector<int> inditer = ind.begin();
for (size_t fast = 0; fast != a.size(); ++fast) {
    if (inditer != ind.end() && *inditer == fast) {
        // "remove" this element by ignoring it
        ++inditer;
    } else {
        a[slow] = a[fast];
        ++slow;
    }
}
a.resize(slow);

STL (), "" ind, , .

+3

Source: https://habr.com/ru/post/1015914/


All Articles