-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvector.cpp
More file actions
94 lines (81 loc) · 1.6 KB
/
vector.cpp
File metadata and controls
94 lines (81 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <iostream>
#include <vector>
using namespace std;
class vec {
public:
vec() {}
vec(int elm, int val):vect(elm, val) {}
int insert_vec(int num);
int delete_vec(int num);
int find_vec(int num);
int size_vec();
~vec() {}
private:
vector<int> vect;
};
int vec::insert_vec(int num)
{
vect.push_back(num);
return 0;
}
int vec::delete_vec(int num)
{
if (vect.empty()) {
cout << "empty" << endl;
return -1;
}
vector<int>::iterator iter;
for(iter = vect.begin(); iter != vect.end(); iter++)
{
if (*iter == num) {
// return the next element, so the step is
// 1. erase, 2. iter++, total add 2 times.
// so need iter --
vect.erase(iter);
//iter --;
}
}
return vect.size();
}
int vec::find_vec(int num)
{
if (vect.empty()) {
cout << "empty" << endl;
return -1;
}
for(int i = 0; i < vect.size(); i++)
{
if (vect[i] == num) {
return vect[i];
}
}
return -1;
}
int vec::size_vec()
{
if (vect.empty()) {
cout << "empty" << endl;
return 0;
} else {
return vect.size();
}
}
int main(void)
{
vec vecc;
for (int i = 0; i < 10; i++)
{
vecc.insert_vec(i);
}
cout << "the size is "<< vecc.size_vec() << endl;
cout << vecc.find_vec(3) << endl;
vecc.delete_vec(8);
cout << "the size is " << vecc.size_vec() << endl;
vec vecc2(10, 5);
cout << "the 2 size is "<< vecc2.size_vec() << endl;
cout << vecc2.find_vec(3) << endl;
// why the rest size is 5?
cout << "the rest is " << vecc2.delete_vec(5) << endl;
cout << "the 2 size is " << vecc2.size_vec() << endl;
return 0;
}