Given
std::vector<double> a;
std::vector<int> ind;
where ind
is 1sorted 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 doesn't feel right to use the std::numeric_limits::max() as a flag in this context.
Of course feelings shouldn't play too much into the equation ... clearly comparing the doubles within the std::remove is safe, and the limit will never occur in practice in this vector in a working application, so it should be ok, no?
Any thoughts on this?
1) Ref comment by the OP. – Alf
ind
are in increasing order and without duplicates, but you don't actually say so in your question. – Scrotumstd::numeric_limits<double>::infinity()
orstd::numeric_limits<double>::quiet_NaN()
instead, if it is known that none of the values in the arrays will be that value. – Incogitabledouble a=1./0;
thenstd::isinf(a)
evaluates to true. Not sure about the exception. In my case I could check for infs upfront since they should not occur in my context. But it seems it might be better to implement my own erase-remove idiom which can use the entries inind
rather than the values do identify entries to delete. – Labbestd::numeric_limits<double>::max()
is already a number in the vector, and hence the operation will fail. Ideally, I would have wanted to reserve a "special" double which I could have used as a flag, for example by usingstd::numeric_limits<double>::max()
as the flag, but then at the same time reducing the max double for everybody else to the second-to-largest possible double value. – Labbe