首页 > 技术文章 > vector存放内置数据类型(2)

huanian 2020-04-28 17:24 原文

容器:vector

算法:for_each

迭代器:vector<int>::iterator

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 using namespace std;
 5 
 6 //为第三种遍历方式提供函数名
 7 void myPrint(int val)
 8 {
 9     cout << val << endl;
10 }
11 
12 //vector存放内置的数据类型
13 void test_01(void)
14 {
15     //创建了一个vector容器,数组
16     vector<int> v;
17 
18     //向容器插入数据
19     v.push_back(10);
20     v.push_back(20);
21     v.push_back(30);
22     v.push_back(40);
23 
24     ////通过迭代器访问容器中的数据
25     //vector<int>::iterator itBegin = v.begin();//起始迭代器 指向容器中的第一个元素位置
26     //vector<int>::iterator itEnd = v.end();//结束迭代器 指向容器中最后一个元素的下一个位置
27 
28     ////第一种遍历方式
29     //while(itBegin != itEnd)
30     //{
31     //    cout << *itBegin << endl;
32     //    itBegin++;
33     //}
34 
35     ////第二种遍历方法
36     //for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
37     //{
38     //    cout << *it << endl;
39     //}
40 
41     //第三种遍历方式    利用STL种提供的算法for_each
42     for_each(v.begin(), v.end(), myPrint);//为什么这里写函数名就可以?
43 }
44 
45 int main(void)
46 {
47     test_01();
48 
49     system("pause");
50     return 0;
51 }
1 //第三种遍历方式    利用STL种提供的算法for_each
2     for_each(v.begin(), v.end(), myPrint);//为什么这里写函数名就可以?

查看一下for_each的源码就知道了,相当于使用了回调函数技术

 1     // FUNCTION TEMPLATE for_each
 2 template<class _InIt,
 3     class _Fn> inline
 4     _Fn for_each(_InIt _First, _InIt _Last, _Fn _Func)
 5     {    // perform function for each element [_First, _Last)
 6     _Adl_verify_range(_First, _Last);
 7     auto _UFirst = _Get_unwrapped(_First);
 8     const auto _ULast = _Get_unwrapped(_Last);
 9     for (; _UFirst != _ULast; ++_UFirst)
10         {
11         _Func(*_UFirst);
12         }
13 
14     return (_Func);
15     }

 

推荐阅读