forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvectors2.cpp
More file actions
58 lines (49 loc) · 1.42 KB
/
Copy pathvectors2.cpp
File metadata and controls
58 lines (49 loc) · 1.42 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
#include<iostream>
#include<vector>
using namespace std;
class MyClass {
private:
int num;
public:
explicit MyClass(int x=0) : num(x) {}
MyClass(const MyClass & original) {
cout << " Copy constructor" << original.num << endl;
num = original.num;
}
void print() const { cout << "num = " << num << endl; }
void change(int x) { num = x; }
};
void printMyClassVector(const vector<MyClass>& v) {
cout << "Printing from printMyClassVector:" << endl;
for (MyClass const &ii : v) {
cout << " ";
ii.print();
}
cout << endl;
}
int main() {
vector<MyClass> vec1; // Vector of objects
vector<MyClass*> vec2; // Vector of pointers
MyClass var;
// Add elements to the vector
for (int ii=1;ii<=5;ii++) {
cout << "Adding MyClass " << ii << ": " << endl;;
var.change(ii);
vec1.push_back(var);
// vec2.push_back(&var); // This adds same pointer to the vector
vec2.push_back(new MyClass(ii*10));
cout << endl;
}
cout << endl << endl << "vec1: " << endl;
for (MyClass const &ii : vec1) {
ii.print();
}
cout << endl;
cout << "vec2: " << endl;
for (MyClass * const&ii : vec2) {
ii->print();
}
cout << endl;
printMyClassVector(vec1);
// printMyClassVector(vec2); // ERROR: vec2 holds a different type than vec1
}