c++中用到迭代器访问容器的有很多,简单举例set中的访问方法,给set中扔进几个随机数,c++中set会自动从小到大排序,然后用迭代器访问方式访问其中的元素:
#include <iostream>
#include <stdlib.h>
#include <set>
using namespace std;
int main()
{
set <int> q;
for(int i = 0; i < 10; i++)
q.insert(rand());
for(set <int> :: iterator it = q.begin(); it != q.end(); it++) //迭代器
cout << *it << endl;
return 0;
}
python中有迭代器数据类型,而且迭代方式更为灵活,要迭代之前只需要判断是否为迭代器数据类型即可(python中的迭代器数据类型有很多),若是直接迭代:
from collections import Iterable #导入Iterable包
s = "stragaga"
num = 442626
if isinstance(s, Iterable):
for c in s:
print(c, end = "") # end = ""为了输出不换行
else:
print("s不是迭代类型")
print("") #输出一个换行
if isinstance(num, Iterable):
for i in num:
print(i, Iterable)
else:
print("num不是迭代类型")
python中对列表和dict迭代示例,见代码:
from collections import Iterable
l = ['a', 'g', 'w', 'j'] #列表
if isinstance(l, Iterable):
for c in l:
print(c, end = "")
print("")
dict = {'a': 1, 'b': 3, 'c': 5} #字典
if isinstance(dict, Iterable):
for key, value in dict.items(): #dict.items()表示对键值同时迭代 dict.keys()表示对键迭代 dict.values()表示对值迭代
print(key, value)
/*学习笔记有错请您指出不要喷就行哈哈,一起进步*/