c++ 遍历vector , set , map

vector ,set ,和map 属于c++ 的三种容器;遍历三种容器的重要方式是创建iterator ,迭代器在这里扮演了类似指针的角色,用迭代器来指向要访问的索引的值。

1: map  类似于python里面的字典。

#include <map>  
  
#include <string>  
  
#include <iostream>  
  
using namespace std;  
int main()  
  
{  
  
    map<int, string> mapStudent;  
  
    mapStudent.insert(pair<int, string>(1, "student_one"));  
  
    mapStudent.insert(pair<int, string>(2, "student_two"));  
  
    mapStudent.insert(pair<int, string>(3, "student_three"));  

    map<int,string>::iterator iter;//please attention the name of  map,not name mapstudent 
    for(iter = mapStudent.begin();iter!=mapStudent.end();iter++)
       cout<<iter->first<<' '<<iter->second<<endl;
    
}  

2:set 里面不能容纳相同的元素

#include <set>
#include <iostream>
using namespace std;
int main() {
	set<int> iset;
	iset.insert(1);
	iset.insert(2);
	iset.insert(3);
	iset.insert(3);
	for (set<int>::iterator iter = iset.begin(); iter != iset.end(); ++iter)
		cout << *iter << endl;
	system("pause");
}

3:vector :

#include <iostream>  
#include <string> 
#include <vector> 
#include <algorithm>
using namespace std;
int main(){
  
    vector<vector<int> >res={{-1, 0, 1},{2, -1, -4}};
    int count = res.size();
    cout<<count<<endl;
    
    for(int i=0;i<count;i++){
        int  sun_len=res[i].size();
        for(int j=0;j<sun_len;j++)
            cout<<res[i][j];
        cout<<endl;

    }

    return 0;
}
#include <vector>
#include <iostream>
using namespace std; 
int main() {
    vector<int> ivec;
    ivec.push_back(1);
    ivec.push_back(2);
    ivec.push_back(3);
    ivec.push_back(4);
    for(vector<int>::iterator iter = ivec.begin();iter != ivec.end(); ++iter)
        cout << *iter << endl;
}

引用:https://blog.csdn.net/leviopku/article/details/82804227

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值