-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path63vectors.cpp
More file actions
77 lines (71 loc) · 2.36 KB
/
Copy path63vectors.cpp
File metadata and controls
77 lines (71 loc) · 2.36 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
#include <iostream>
#include <cstring>
#include <fstream>
#include <vector> // Header file for accessing vector containers for STL
using namespace std;
template <class T>
void display(vector<T> &v)
{
cout << "Elements of vector : " << endl;
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " ";
// a function to find the position of the element
cout << "[ "<<v.at(i)<<" ] ";
}
cout << endl;
}
int main()
{
/*
SYNTAX FOR VECTORS :
Since vectors are template classes, to use them simply use the object declaration syntax
we use with normal template classes such as {{class name (vector in this case)}} <data_type> {{object_name}};
Use website cplusplus.com to access different commands to use with vector
for example :
*/
vector<int> vec1;
int element, size;
cout << "Tell the size for your vector??" << endl;
cin >> size;
for (int i = 0; i < size; i++)
{
cout << "Enter an element to the vector : ";
cin >> element;
vec1.push_back(element);
}
cout << endl;
display(vec1);
/*
a command function to add a random element to the vector at a specified location using iterators it is called insert()
create an iterator
syntax:
vector <data_type> :: iterator iterator_name = object_vector.begin(); here begin specifies the position
*/
vector<int>::iterator iter = vec1.begin();
vec1.insert(iter, 69);
display(vec1);
/*
insert syntax :
object.insert(iterator (use pointer arithmetic to shift the pointer), frequency (1 if not specified), element to be added )
*/
vec1.insert(iter+2, 4, 420);
display(vec1);
// another command or function that can remove the last element of the vector
vec1.pop_back();
display(vec1);
/*
DIFFERENT WAYS TO INITIALIZE A VECTOR OBJECT
vector <data_type> object_name(size);
then use push_back to enter elements to it
live examples :
*/
vector <char> vec2(5); // here only one argument specifies the size
vec2.push_back('k');
display(vec2);
vector <char> vec3(vec2); // this vector 3 takes the reference to vector 2
display(vec3);
vector <float> vec4(5, 3.4); // first argument specifies the size, second specifies the element then that element is repeated
display(vec4);
return 0;
}