I have this situation:
for(auto it = vec.rbegin(); it != vec.rend(); ++it)
{
if(condition(it))
{
//Move it at end;
break;
}
}
What is the most efficient/elegant way to move *it
at the end of vec
?
EDIT: *it
, not it
EDIT1: Now I use:
auto val = *it;
vec.erase((++it).base());
vec.push_back(val);
But I don't think is very efficient...
To move it to the end:
for(auto it = vec.rbegin(); it != vec.rend(); ++it)
{
if(condition(it))
{
auto val = *it;
vec.erase((++it).base());
vec.push_back(val);
break;
}
}
To swap with the last element:
for(auto it = vec.rbegin(); it != vec.rend(); ++it)
{
if(condition(it))
{
auto it2 = --vec.end();
auto val = *it;
*it = *it2;
*it2 = val;
break;
}
}
If prefer standard algorithms over manual loops. So I'd use std::find_if .
If you need to preserve the order of the elements, moving to the end can be done using std::rotate :
auto rit = std::find_if(vec.rbegin(), vec.rend(), [](int i){ return i == 6; });
if (rit != vec.rend()) {
auto it = rit.base();
std::rotate(it-1, it, vec.end());
}
If you don't need to keep the order, you can use std::iter_swap :
auto it = std::find_if(vec.rbegin(), vec.rend(), [](int i){ return i == 6; });
if (it != vec.rend())
std::iter_swap(it, vec.rbegin());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.