C++ Vector遍历的几种方式


    
    
  1. #include <vector>
  2. #include <iostream>
  3. using namespace std;
  4. struct Point
  5. {
  6. double x;
  7. double y;
  8. Point()
  9. {
  10. x = 0;
  11. y = 0;
  12. }
  13. };
  14. int main()
  15. {
  16. vector<Point> m_testPoint;
  17. m_testPoint. clear();
  18. m_testPoint. shrink_to_fit();
  19. for ( int i = 0; i< 10; ++i)
  20. {
  21. Point temp;
  22. temp.x = i*i;
  23. temp.y = i*i;
  24. m_testPoint. push_back(temp);
  25. }
  26. //第一种遍历方式,下标
  27. cout << "第一种遍历方式,下标访问" << endl;
  28. for ( int i = 0; i<m_testPoint. size(); ++i)
  29. {
  30. cout << m_testPoint[i].x << " " << m_testPoint[i].y << endl;
  31. }
  32. //第二种遍历方式,迭代器
  33. cout << "第二种遍历方式,迭代器访问" << endl;
  34. for (vector<Point>::iterator iter = m_testPoint. begin(); iter != m_testPoint. end(); iter++)
  35. {
  36. cout << (*iter).x << " " << (*iter).y << endl;
  37. }
  38. //第三种遍历方式,auto关键字
  39. cout << "C++11,第三种遍历方式,auto关键字" << endl;
  40. for ( auto iter = m_testPoint. begin(); iter != m_testPoint. end(); iter++)
  41. {
  42. cout << (*iter).x << " " << (*iter).y << endl;
  43. }
  44. //第四种遍历方式,auto关键字的另一种方式
  45. cout << "C++11,第四种遍历方式,auto关键字" << endl;
  46. for ( auto i : m_testPoint)
  47. {
  48. cout << i.x << " " << i.y << endl;
  49. }
  50. return 0;
  51. }


如果您觉得这篇博文有用,请访问我的个人站:http://www.stubbornhuang.com/​​​​​​,更多博文干货等着您。

转载于 https://blog.csdn.net/HW140701/article/details/78833486?app_version=5.8.0&csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%2278833486%22%2C%22source%22%3A%22Dayu_log%22%7D&utm_source=app。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值