将向量元素移动到向量的后面 [英] Moving a vector element to the back of the vector

查看:33
本文介绍了将向量元素移动到向量的后面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有比擦除元素并将其重新添加到后面更好的方法(更快或使用更少的代码符号)?

Is there any better way (either faster or with fewer symbols of code) than erasing the element and re-adding it to the back?

template <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
   T tmp(v[itemIndex]);
   v.erase(v.begin() + itemIndex);
   v.push_back(tmp);
}

推荐答案

您可以使用 std::rotate 来自标准库.由于这不会改变矢量大小,因此也不会触发重新分配.你的函数看起来像这样:

You can do this with std::rotate from the standard library. Since this doesn't change the vector size it also won't trigger a reallocation. Your function would look something like this:

template <typename T>
void moveItemToBack(std::vector<T>& v, size_t itemIndex)
{
    auto it = v.begin() + itemIndex;
    std::rotate(it, it + 1, v.end());
}

这篇关于将向量元素移动到向量的后面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆