python与c++中的迭代器使用示例

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)

/*学习笔记有错请您指出不要喷就行哈哈,一起进步*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值