-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveAllOccurrencesOfAnElement.cpp
More file actions
65 lines (50 loc) · 1.15 KB
/
RemoveAllOccurrencesOfAnElement.cpp
File metadata and controls
65 lines (50 loc) · 1.15 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
/**
* \file RemoveAllOccurrencesOfAnElement.cpp
* \brief
*
* \todo
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
void removeAllMatchingElements_nonEfficient(std::vector<int> & vec, int elem)
{
std::vector<int>::iterator it = vec.begin();
while(it != vec.end())
{
if(*it == elem)
{
it = vec.erase(it);
}
else
it++;
}
}
void removeAllMatchingElements_Efficient(std::vector<int> & vec, int elem)
{
vec.erase(std::remove(vec.begin(), vec.end(), elem), vec.end());
}
void displayVector(std::vector<int> & vec)
{
std::vector<int>::iterator it = vec.begin();
while(it != vec.end())
std::cout << (*it++) << " ";
std::cout<<std::endl;
}
int main()
{
int arr[10] = {1,2,5,4,5,1,5,7,8,9};
std::vector<int> vec(arr , arr + 10);
cout << "Original Vector is " << endl;
for (int x : vec)
cout << x << " ";
cout << "\n" << endl;
removeAllMatchingElements_nonEfficient(vec, 5);
displayVector(vec);
std::vector<int> vec2(arr , arr + 10);
removeAllMatchingElements_Efficient(vec2, 5);
displayVector(vec2);
return 0;
}