Skip to content

Commit 4e3fbe1

Browse files
committed
+ ch3_iterator
1 parent ecdfa1e commit 4e3fbe1

1 file changed

Lines changed: 66 additions & 0 deletions

File tree

EssentialCPP/ch3_iterator.cpp

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#include <iostream>
2+
#include <list>
3+
#include <string>
4+
#include <vector>
5+
using namespace std;
6+
7+
template<typename T>
8+
void display(const vector<T> &vec, ostream &os)
9+
{
10+
for(auto cbeg = vec.cbegin(),
11+
cend = vec.cend();
12+
cbeg != cend; ++cbeg)
13+
os << *cbeg << " ";
14+
os << endl;
15+
}
16+
17+
template<typename Iter, typename T>
18+
Iter find(Iter first, Iter last, const T &value)
19+
{
20+
for(; first != last; ++first)
21+
if(value == *first)
22+
return first;
23+
return last;
24+
}
25+
26+
27+
int main()
28+
{
29+
vector<string> vs = {"a", "bc", "def"};
30+
for(auto it = vs.cbegin(); it != vs.cend(); ++it)
31+
{
32+
cout << *it << " ";
33+
cout << it->size() << endl;
34+
}
35+
cout << endl;
36+
37+
display(vs, cout);
38+
39+
cout << "find demo:" << endl;
40+
const int SIZE = 8;
41+
int ia[SIZE] = {1,1,2,3,5,8,13,21};
42+
vector<int> ivec(ia, ia+SIZE);
43+
list<int> ilist(ia, ia+SIZE);
44+
int *pia = find(ia, ia+SIZE, 1024);
45+
46+
if(pia != ia+SIZE)
47+
cout << "found in array" << endl;
48+
else
49+
cout << "not found in array" << endl;
50+
51+
vector<int>::iterator it;
52+
it = find(ivec.begin(), ivec.end(), 21);
53+
if(it != ivec.end())
54+
cout << "found in vector\n";
55+
else
56+
cout << "not found in vector\n";
57+
58+
list<int>::iterator iter;
59+
iter = find(ilist.begin(), ilist.end(), 13);
60+
if(iter != ilist.end())
61+
cout << "found in list\n";
62+
else
63+
cout << "not found in list\n";
64+
65+
return 0;
66+
}

0 commit comments

Comments
 (0)