[英]std::vector move reverse iterator at end
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
? 在
vec
末尾移动*it
的最有效/最优雅的方法是什么?
EDIT: *it
, not it
编辑:
*it
,不是it
EDIT1: Now I use: EDIT1:现在我使用:
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 .
因此,我将使用std :: find_if 。
If you need to preserve the order of the elements, moving to the end can be done using std::rotate : 如果您需要保留元素的顺序,则可以使用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 : 如果不需要保留订单,可以使用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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.