C++ vector 赋值、删除、排序类之外的其他函数

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>容器的元素只有01,有其他数则警告并强制转换。
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
请按任意键继续. . .
*/ 

vector 相关文章:

C++ vector声明和赋值的相关函数

C++ vector容器的多种遍历方式

C++ vector 删除和排序的相关函数

C++ vector 赋值、删除、排序类之外的其他函数

C++ vector 容器的全排列算法 next_permutation

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hann Yang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值