C++迭代器使用

#include <vector>
#include <iostream>
#include<stdlib.h>
#include <algorithm>  
using namespace std;


void func(double x)
{
cout << "value:" << x << endl;
}
int main()
{
vector <int> rating(5);
int n;
cin >> n;
vector <double> scores(n);


rating[0] = 9;
for (int i = 0; i < n; i++)
{
cout << "scores["<< i <<"]="<<scores[i] << endl;
}


for (int i = 0; i < n; i++)
{
cout << "scores[" << i << "]=" << scores[i] << endl;
}


vector<double>::iterator pd; //pd是 vector<double>的一个迭代器
int i = 1;
for (pd = scores.begin(); pd != scores.end(); pd++,i++) 
{
*pd = i*1.1;
}

i = 0;
for (pd = scores.begin(); pd != scores.end(); pd++, i++)
{
cout << "scores[" << i << "]=" << *pd <<endl;
}
double x = 12.5;

i = 0;
scores.push_back(x);//将x插入到容器的末尾
for (pd = scores.begin(); pd != scores.end(); pd++, i++)
{
cout << "scores[" << i << "]=" << *pd << endl;



i = 0;
scores.erase(scores.begin(), scores.begin() + 3);;//将容器从开始第一个元素到之后的3个元素从容器中删除
for (pd = scores.begin(); pd != scores.end(); pd++, i++)
{
cout << "scores[" << i << "]=" << *pd << endl;
}




scores.insert(scores.begin()+1, 3.5);//在容器scores的开始+1的位置插入元素3.5
i = 0;
for (pd = scores.begin(); pd != scores.end(); pd++, i++)
{
cout << "scores[" << i << "]=" << *pd << endl;
}

for_each(scores.begin(), scores.end(), func);//socres中每个元素都调用一次func函数
random_shuffle(scores.begin(),scores.end()-1);//将scores中除最后一个元素外,其余的全部随机排列
for_each(scores.begin(), scores.end(), func);//socres中每个元素都调用一次func函数
sort(scores.begin(), scores.end());//scores中的数据按照升序进行排列
for_each(scores.begin(), scores.end(), func);//socres中每个元素都调用一次func函数
//模板使得算法独立于存储的数据类型,迭代器使得算法独立于使用的容器的类型
//应该能够对迭代器执行解除引用的操作,以便能访问值,if p是迭代器,then *p 需要可以访问
//迭代器之间可以赋值, if q p 都是迭代器 ,则q =p 需要定义
// 迭代器之间应可以比较  if q p都是迭代器 ,则 q==p q!=p 应该定义
//应能够使用迭代器遍历容器中所有元素
system("pause");
return 0;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值