您的位置:首页 > 其它

STL_Iterator

2016-06-25 14:19 309 查看
迭代器iterator是一个很神奇的东西。

STL的中心思想在于:将数据容器和算法分开,彼此独立设计,最后再以胶合剂(iterator)将他们撮合在一起。

#pragma once

#include<algorithm>
#include<vector>
#include<list>
#include<string>
void TestVector()
{
vector<int> v;
v.push_back(1);
v.push_back(4);
v.push_back(3);
v.push_back(2);

vector<int>::iterator it = v.begin();
while (it != v.end())
{
cout << *it << " ";
++it;
}
cout << endl;
//STL排序头文件在algorithm
sort(v.begin(), v.end());

for (it=v.begin(); it < v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
}

void TestList()
{
list<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);

list<int>::iterator it = l.begin();
while (it != l.end())
{
cout << *it << " ";
it++;
}
cout << endl;
//替换函数
replace(l.begin(), l.end(), 3, 4);

it = l.begin();
while (it != l.end())
{
cout << *it << " ";
it++;
}
}

void Test3()
{
list<string> ls;
ls.push_back("aa");
ls.push_back("bb");
ls.push_back("cc");
ls.push_back("dd");

list<string>::iterator it = ls.begin();
while (it != ls.end())
{
cout << *it << " ";
++it;
}
cout << endl;

//find
it = find(ls.begin(), ls.end(), "aa");
//it = find(ls.begin(), ls.end(), "ee"TL);
if (it != ls.end())//如果查找失败(不存在),it就会返回ls.end()
cout << *it << endl;
else
cout << "find false" << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: