当前位置:网站首页>STL源码剖析:迭代器的概念理解,以及代码测试。
STL源码剖析:迭代器的概念理解,以及代码测试。
2022-07-30 05:49:00 【夕阳染色的坡道】
目的:理解STL源码
迭代器的缘由来自于一种设计模式。它提供一个方法,让用户能够一一的访问里面的数据,而不用管里面的数据的组成的结构(树状,线性,数组,图等结构)。它不同于数据结构的访问样子,它统一的一一访问完整的数据。
在STL中迭代器不但能够一一访问里面的数据,它同时可以作为一个粘合剂,将数据结构和算法分开。数据结构和算法分来,不但能够易于阅读和写代码,同时符合开发中的开闭原则。如果每个数据结构用一个算法,算法可以在别处开发,然后用迭代器把数据结构和算法粘合在一起。具体测试如下:数据结构有vector, list, deque三种;算法有find一种。find算法应用于这三种数据结构中。具体代码如下:
#include<vector>
#include<list>
#include<deque>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
const int arraysize = 7;
int ia[arraysize] = {
0,1,2,3,4,5,6};
vector<int> ivect(ia, ia+arraysize);
list<int> ilist(ia, ia+arraysize);
deque<int> ideque(ia, ia+arraysize);
vector<int>::iterator it1 = find(ivect.begin(), ivect.end(), 4);
if(it1 == ivect.end())
{
cout<<"4 not found in ivect.. "<<std::endl;
}
else
{
cout << "4 found in ivect..."<<std::endl;
}
list<int>::iterator it2 = find(ilist.begin(), ilist.end(), 5);
if(it2 == ilist.end())
{
cout << "5 not found in ilist... " << endl;
}
else
{
cout << "5 found in ilist... " << endl;
}
deque<int>::iterator it3 = find(ideque.begin(), ideque.end(), 6);
if(it3 == ideque.end())
{
cout << "6 not found in ideque... " << endl;
}
else
{
cout << "6 found in ideque... " << endl;
}
return 0;
}
代码中,搜索功能的find应用到三种数据结构中,它测试结果如下:
它能找到4,5,6。应用了搜索功能,这也是迭代器的一个非常重要的作用。
感悟:STL的设计非常精巧,迭代器也是一个非常重要的部分,对以后自己在代码上设计提供一个技巧。以后尽量将基础算法和数据结构分开,再用迭代器去实现算法和数据结构的融合。
边栏推荐
猜你喜欢
随机推荐
Advanced multi-threading (lock strategy, spin+CAS, Synchronized, JUC, semaphore)
Selenium01
A New Paradigm for Distributed Deep Learning Programming: Global Tensor
Test and Development Engineer Growth Diary 009 - Environment Pai Pai Station: Development Environment, Test Environment, Production Environment, UAT Environment, Simulation Environment
Redis下载与安装
远程连接服务器的MySql
how to use xilinx's FFT ip
flask项目快速搭建部署gunicorn+supervisor
多线程进阶(锁策略,自旋+CAS,Synchronized,JUC,信号量)
MongoDB - Introduction, Data Types, Basic Statements
Multithreading basics (multithreaded memory, security, communication, thread pools and blocking queues)
关于memcache内核,全网最通俗的讲解
测试开发工程师成长日记017 - bug的生命周期
基于 JupyterLab 插件在 GraphScope 中交互式构图
Test Development Engineer Growth Diary 007 - Bug Priority Definition and Filling Specifications
网络协议01 - 基础概念
测试开发工程师成长日记003 - 接口自动化框架搭建
向量三重积的等式推导证明
作为测试leader,考察求职者的几个方面
The concept and testing method of black box testing








