C++迭代器使用

来源:互联网 发布:淘宝上尺码是什么意思 编辑:程序博客网 时间:2024/06/01 08:19
#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;
}
原创粉丝点击