c++ - 一种交换 vector 的方法,可能吗?

标签 c++ stl swap

<分区>

在 C++98 中,这是我想要做的(这不起作用,因为 _M_start 等是私有(private)成员):

void vectormove(std::vector<int>& a, std::vector<int>& b)
{
    a._M_impl._M_start = b._M_impl._M_start;
    a._M_impl._M_finish = b._M_impl._M_finish;
    a._M_impl._M_end_of_storage = b._M_impl._M_end_of_storage;
}

这就是我想要的方式

//vectors are predefined already
std::vector<int> a;
std::vector<int> b(10000000,20);

//in later part of code
//a=b;  //expensive copy
//std::swap(a,b);   //inexpensive swap
vectormove(a,b);  //i need an inexpensive one way swap instead

我可能通过松散地使用复制、移动和交换来破坏术语,但我对这个主题没有更好的把握。我希望我能够传达我的意图。

最佳答案

看起来您只是想让a 引用 b 的内部结构。这样做的方法就是:

std::vector<int>& a = b;

如果你想让 a 接管 b 的内部结构,那就是:

std::vector<int> a = std::move(b);

在 C++03 中可以实现为空 vector 交换:

std::vector<int> a;
using std::swap;
swap(a, b);

关于c++ - 一种交换 vector 的方法,可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37102112/

相关文章:

c++ - 通过函数初始化指针

c++ - 如何让 : map<T, vector<iterator to map itself>>?

c++ - std::map :使用自定义运算符时更新 key

c# - 交换字节顺序/字节顺序

Python 简单交换函数

c++ - C++ 流是如何工作的?

c++ - 如何在vscode扩展名中检索C/C++文件的编译命令

python - '::hypot' 尚未声明

c++ - 模板化类构造函数中的 static_assert

c# - 输出不是在同一数组中交换元素的预期输出