swap函数
语法:
1 |
void swap(vector& __x); |
swap() 交换两个Vector
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/** * @brief Swaps data with another %vector. * @param x A %vector of the same element and allocator types. * * This exchanges the elements between two vectors in constant time. * (Three pointers, so it should be quite fast.) * Note that the global std::swap() function is specialized such that * std::swap(v1,v2) will feed to this function. */ void swap(vector& __x) { std::swap(this->_M_impl._M_start, __x._M_impl._M_start); std::swap(this->_M_impl._M_finish, __x._M_impl._M_finish); std::swap(this->_M_impl._M_end_of_storage, __x._M_impl._M_end_of_storage); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; vector<int> v2(3, 2); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); cout<<"v1向量骨元素数:"<<v1.size()<<endl; cout<<"v2向量骨元素数:"<<v2.size()<<endl; v1.swap(v2); //交换 cout<<"v1向量骨元素数:"<<v1.size()<<endl; cout<<"v2向量骨元素数:"<<v2.size()<<endl; } |
测试结果:
1 2 3 4 |
v1向量骨元素数:5 v2向量骨元素数:3 v1向量骨元素数:3 v2向量骨元素数:5 |