move()
移动源容器的一段到目标容器的指定位置,源容器的元素并不改变。
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { vector<int> v1={1,2,3,4,5,6,7}; vector<int> v2={-1,-2,-3,-4,-5}; cout<<"移动前:"<<endl; for(auto v:v1) cout<<v<<" "; cout<<endl; for(auto v:v2) cout<<v<<" "; cout<<endl; move(v2.begin()+1,v2.begin()+3,v1.begin()+4); cout<<"移动后:"<<endl; for(auto v:v1) cout<<v<<" "; cout<<endl; for(auto v:v2) cout<<v<<" "; cout<<endl; return 0; } /*运行结果:即把v2[1] v2[2](区间左开右闭不含v2[3])移动 到v1[4]位置,覆盖相应个位置,v2不发生改变 移动前: 1 2 3 4 5 6 7 -1 -2 -3 -4 -5 移动后: 1 2 3 4 -2 -3 7 -1 -2 -3 -4 -5 -------------------------------- Process exited after 0.481 seconds with return value 0 请按任意键继续. . . */
flip()
对容器元素取反,仅适用于<bool>型容器。
vector<bool> bv={0,1,0x0,0x1,true,false}; //<bool>容器的元素只有0和1,有其他数则警告并强制转换。
swap(bv[i],bv[j])
交换索引号i,j二个元素的位置,也仅适用于<bool>型容器。
#include <iostream> #include <vector> #include <algorithm> #include <bitset> using namespace std; int main(void) { vector<bool> bv={0,1,0x0,0x1,true,false,1}; for(auto v:bv) cout<<v<<" "; cout<<endl; bv.flip(); for(auto v:bv) cout<<v<<" "; cout<<endl; bv.swap(bv.front(),bv.back()); bv.swap(bv.at(2),bv.at(3)); for(auto v:bv) cout<<v<<" "; cout<<endl; return 0; } /*运行结果:第二行是取反的结果,第三行是交换了首和尾及bv[2]和bv[3]的结果 0 1 0 1 1 0 1 1 0 1 0 0 1 0 0 0 0 1 0 1 1 -------------------------------- Process exited after 0.481 seconds with return value 0 请按任意键继续. . . */
data()
返回指向容器第一个元素的指针。type_name *p=vect.dat();
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(void) { vector<int> v1={1,2,3,4,5,6,7,8,9,0}; vector<string> v2={"C","C++","Java","Python"}; int *p=v1.data(); for(auto v:v1) cout<<v<<" "; cout<<endl; for(auto v:v1) cout<<*p<<" "; cout<<endl; //未移动指针 for(auto v:v1) cout<<*p++<<" "; cout<<endl; string *p1=v2.data(); for(auto v:v2) cout<<v<<" "; cout<<endl; for(auto v:v2) cout<<*p1++<<" "; cout<<endl; p1=v2.data(); ++p1; //指针回0后+1 for(int i=1;i<v2.size();i++) cout<<*p1++<<" "; cout<<endl; return 0; } /* 运算结果: 1 2 3 4 5 6 7 8 9 0 1 1 1 1 1 1 1 1 1 1 1 2 3 4 5 6 7 8 9 0 C C++ Java Python C C++ Java Python C++ Java Python -------------------------------- Process exited after 0.7244 seconds with return value 0 请按任意键继续. . . */