0
点赞
收藏
分享

微信扫一扫

C++ 学习笔记 十一

凉夜lrs 2022-01-14 阅读 37

迭代器

访问顺序容器和关联容器中的元素,使用迭代器。

 

#include<iostream>
using namespace std;

struct Node
{
	int num;
	Node* pnext;


};

void addNode(Node *&rpHead,Node *&rpEnd,int id)
{
	Node *ptemp=new Node;
	ptemp->num=id;
	ptemp->pnext=NULL;
	if(rpHead==NULL)
	{
	rpHead=ptemp;

	}
	else
	{
	rpEnd->pnext=ptemp;
	}
	rpEnd=ptemp;

}


class Iterator
{
private:
	Node* pmark;

public:
	Iterator(Node *p)
	{
	this->pmark=p;
	}
public:
	bool operator!=( Node *p);
	int  operator*()
	{
	
		return pmark->num;
	}
	Node*operator++(int n)
	{
	Node*ptemp=pmark;
	pmark=pmark->pnext;
	return ptemp;
	}

};
 
bool Iterator::operator!=(Node *p )
{
	if(pmark!=p)
	return true;

	else
		return false;
}



int main()
{
	Node *pHead=NULL;
	Node *pEnd=NULL;
	addNode(pHead,pEnd,1);
	addNode(pHead,pEnd,2);
	addNode(pHead,pEnd,3);
	Node*pmark=pHead;

	Iterator ite=pHead;
	while(ite!=NULL)
	{
	cout<<*ite<<endl;
	ite++;
	}

	/*while (pmark!=NULL)
	{
		cout<<pmark->num<<endl;
		pmark=pmark->pnext;
	}*/

	system("pause");
return 0;
}

array 数组

#include<array>
#include<iostream>
#include<string>
using namespace std;

int main()
{


	array<int, 5>arr={1,2,3,4,5};   //也有默认初始化
	array<string, 5>arr2={"sdad","sadada"};
	
	//for(int i=0;i<5;i++)
	//{cout<<arr2.at(i)<<endl;
	//}

	//cout<<arr.front()<<endl;
	//cout<<arr.back()<<endl;

	//cout<<arr.size()<<endl;    //返回定义数组的大小
	
	//array<int,5>::iterator ite=arr.begin();
	array<int,5>::reverse_iterator re_ite=arr.rbegin();//反向迭代器
	while(re_ite!=arr.rend())
	{
		cout<<*re_ite<<endl;
	re_ite++;

	}

	system("pause");
return 0;
}

vector 数组

#include<vector>
#include<iostream>
#include<string>
using namespace std;

int main()
{

vector<int>vec(5,2);

vec.push_back(3);
//for(int i=0;i<6;i++)
//{
//cout<<vec[i]<<endl;
//}


vector<int> ::iterator ite=vec.begin();
//while(ite!=vec.end())
//{
//
//	//if(*ite==3)
//	//{
//
//	ite=vec.erase(ite);    删除
//	//	ite=vec.insert(ite,100);
//	//	ite++;
//
//	//}
//
//
//cout<<*ite<<endl;
//
//ite++;
//}

for(int i=0;i<=15;i++)
{
	vec.push_back(i);
	cout<<vec.size()<<"    "<<vec.capacity()<<endl;

}

	

	system("pause");
return 0;
}

list 链表

#include<list>
#include<iostream>
#include<string>
using namespace std;

int main()
{

	list<int> lis;
	lis.push_back(1);
	lis.push_back(2);
	lis.push_back(3);
	lis.push_back(4);
	lis.push_front(100);
	lis.push_front(200);


	list<int>::iterator ite=lis.begin();
	/*while(ite!=lis.end())
	{
	
		cout<<*ite<<endl;
	ite++;
	}*/

	cout<<lis.front()<<endl;
	cout<<lis.back()<<endl;
	cout<<*lis.begin()<<endl;
	cout<<*lis.end()<<endl;
	system("pause");
return 0;
}
举报

相关推荐

0 条评论