[go: up one dir, main page]

0% found this document useful (0 votes)
4 views11 pages

Vector

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Vector

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

C++ Vectors

In C++, vectors are used to store elements of similar data types. However,
unlike arrays, the size of a vector can grow dynamically.
That is, we can change the size of the vector during the execution of a
program as per our requirements.

#include <vector>

C++ Vector Declaration


Once we include the header file, here's how we can declare a vector in C++:

std::vector<T> vector_name;

The type parameter <T> specifies the type of the vector. It can be any primitive
data type such as int , char , float , etc. For example,

vector<int> num;

Here, num is the name of the vector.


Notice that we have not specified the size of the vector during the declaration.
This is because the size of a vector can grow dynamically, so it is not
necessary to define it.

C++ Vector Initialization


There are different ways to initialize a vector in C++.
Method 1:

// Initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};
// Uniform initialization
vector<int> vector2 {1, 2, 3, 4, 5};

Here, we are initializing the vector by providing values directly to the vector.
Now, both vector1 and vector2 are initialized with values 1, 2, 3, 4, 5.
Method 2:

vector<int> vector3(5, 12);

Here, 5 is the size of the vector and 12 is the value.


This code creates an int vector with size 5 and initializes the vector with the
value of 12. So, the vector is equivalent to

vector<int> vector3 = {12, 12, 12, 12, 12};

Example: C++ Vector Initialization


#include <iostream>
#include <vector>
using namespace std;

int main() {

// initializer list
vector<int> vector1 = {1, 2, 3, 4, 5};

// uniform initialization
vector<int> vector2{6, 7, 8, 9, 10};

// method 3
vector<int> vector3(5, 12);

cout << "vector1 = ";


// ranged loop
for (const int& i : vector1) {
cout << i << " ";
}

cout << "\nvector2 = ";

// ranged loop
for (const int& i : vector2) {
cout << i << " ";
}

cout << "\nvector3 = ";

// ranged loop
for (int i : vector3) {
cout << i << " ";
}

return 0;
}
Run Code

Output

vector1 = 1 2 3 4 5
vector2 = 6 7 8 9 10
vector3 = 12 12 12 12 12

Here, we have declared and initialized three different vectors using three
different initialization methods and displayed their contents.

Basic Vector Operations


The vector class provides various methods to perform different operations on
vectors. We will look at some commonly used vector operations in this tutorial:
 Add elements

 Access elements
 Change elements

 Remove elements

1. Add Elements to a Vector


To add a single element into a vector, we use the push_back() function. It
inserts an element into the end of the vector. For example,
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> num {1, 2, 3, 4, 5};

cout << "Initial Vector: ";

for (const int& i : num) {


cout << i << " ";
}

// add the integers 6 and 7 to the vector


num.push_back(6);
num.push_back(7);

cout << "\nUpdated Vector: ";

for (const int& i : num) {


cout << i << " ";
}

return 0;
}
Run Code

Output

Initial Vector: 1 2 3 4 5
Updated Vector: 1 2 3 4 5 6 7

Here, we have initialized an int vector num with the elements {1, 2, 3, 4, 5} .

Notice the statements

num.push_back(6);
num.push_back(7);

Here, the push_back() function adds elements 6 and 7 to the vector.

Note: We can also use the insert() and emplace() functions to add elements
to a vector.

2. Access Elements of a Vector


In C++, we use the index number to access the vector elements. Here, we
use the at() function to access the element from the specified index. For
example,
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> num {1, 2, 3, 4, 5};

cout << "Element at Index 0: " << num.at(0) << endl;


cout << "Element at Index 2: " << num.at(2) << endl;
cout << "Element at Index 4: " << num.at(4);

return 0;
}
Run Code

Output
Element at Index 0: 1
Element at Index 2: 3
Element at Index 4: 5

Here,

 num.at(0) - access element at index 0


 num.at(2) - access element at index 2
 num.at(4) - access element at index 4
Note: Like an array, we can also use the square brackets [] to access vector
elements. For example,

vector<int> num {1, 2, 3};


cout << num[1]; // Output: 2

However, the at() function is preferred over [] because at() throws an


exception whenever the vector is out of bound, while [] gives a garbage
value.

vector<int> num {1, 2, 3};

// gives garbage value


cout << num[4];

// throws an exception
cout << num.at(4);

3. Change Vector Element


We can change an element of the vector using the same at() function. For
example,
#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> num {1, 2, 3, 4, 5};

cout << "Initial Vector: ";

for (const int& i : num) {


cout << i << " ";
}

// change elements at indexes 1 and 4


num.at(1) = 9;
num.at(4) = 7;

cout << "\nUpdated Vector: ";

for (const int& i : num) {


cout << i << " ";
}

return 0;
}
Run Code

Output

Initial Vector: 1 2 3 4 5
Updated Vector: 1 9 3 4 7

In the above example, notice the statements,

num.at(1) = 9;
num.at(4) = 7;

Here, we have assigned new values to indexes 1 and 4. So the value at index
1 is changed to 9 and the value at index 4 is changed to 7.

4. Delete Elements from C++ Vectors


To delete a single element from a vector, we use the pop_back() function. For
example,
#include <iostream>
#include <vector>

using namespace std;

int main() {
vector<int> prime_numbers{2, 3, 5, 7};

// initial vector
cout << "Initial Vector: ";
for (int i : prime_numbers) {
cout << i << " ";
}

// remove the last element


prime_numbers.pop_back();

// final vector
cout << "\nUpdated Vector: ";
for (int i : prime_numbers) {
cout << i << " ";
}

return 0;
}
Run Code

Output

Initial Vector: 2 3 5 7
Updated Vector: 2 3 5

In the above example, notice the statement,

prime_numbers.pop_back();

Here, we have removed the last element (7) from the vector.
====================================================================

C Program to Implement Vector


This is a C Program to implement Vectors. An array (vector) is a common-place data type,
used to hold and describe a collection of elements. These elements can be fetched at
runtime by one or more indices (identifying keys). A distinguishing feature of an array
compared to a list is that they allow for constant-time random access lookup, compared to
the latters sequential access. Resizable arrays allow for an unspecified upper-bound of
collection elements at runtime, and are conceptuality similar to a list. These dynamic arrays
are more complicated and less used in introduction to its compatriot list, which is dynamic
by nature. Using C as the language of implementation this post will guide you through
building a simple vector data-structure. The structure will take advantage of a fixed-size
array, with a counter invariant that keeps track of how many elements are currently present.
If the underlying array becomes exhausted, the addition operation will re-allocate the
contents to a larger size, by way of a copy.
Here is source code of the C Program to Implement Vector. The C program is successfully
compiled and run on a Linux system. The program output is also shown below.

1.#include <stdio.h>
2.#include <stdlib.h>
3.
4.#ifndef VECTOR_H
5.#define VECTOR_H
6.
7.#define VECTOR_INIT_CAPACITY 4
8.
9.#define VECTOR_INIT(vec) vector vec; vector_init(&vec)
10. #define VECTOR_ADD(vec, item) vector_add(&vec, (void *) item)
11. #define VECTOR_SET(vec, id, item) vector_set(&vec, id, (void
*) item)
12. #define VECTOR_GET(vec, type, id) (type) vector_get(&vec, id)
13. #define VECTOR_DELETE(vec, id) vector_delete(&vec, id)
14. #define VECTOR_TOTAL(vec) vector_total(&vec)
15. #define VECTOR_FREE(vec) vector_free(&vec)
16.
17. typedef struct vector {
18. void **items;
19. int capacity;
20. int total;
21. } vector;
22.
23. void vector_init(vector *);
24. int vector_total(vector *);
25. static void vector_resize(vector *, int);
26. void vector_add(vector *, void *);
27. void vector_set(vector *, int, void *);
28. void *vector_get(vector *, int);
29. void vector_delete(vector *, int);
30. void vector_free(vector *);
31.
32. #endif
33.
34. void vector_init(vector *v) {
35. v->capacity = VECTOR_INIT_CAPACITY;
36. v->total = 0;
37. v->items = malloc(sizeof(void *) * v->capacity);
38. }
39.
40. int vector_total(vector *v) {
41. return v->total;
42. }
43.
44. static void vector_resize(vector *v, int capacity) {
45. #ifdef DEBUG_ON
46. printf("vector_resize: %d to %d\n", v->capacity,
capacity);
47. #endif
48.
49. void **items = realloc(v->items, sizeof(void *) *
capacity);
50. if (items) {
51. v->items = items;
52. v->capacity = capacity;
53. }
54. }
55.
56. void vector_add(vector *v, void *item) {
57. if (v->capacity == v->total)
58. vector_resize(v, v->capacity * 2);
59. v->items[v->total++] = item;
60. }
61.
62. void vector_set(vector *v, int index, void *item) {
63. if (index >= 0 && index < v->total)
64. v->items[index] = item;
65. }
66.
67. void *vector_get(vector *v, int index) {
68. if (index >= 0 && index < v->total)
69. return v->items[index];
70. return NULL;
71. }
72.
73. void vector_delete(vector *v, int index) {
74. if (index < 0 || index >= v->total)
75. return;
76.
77. v->items[index] = NULL;
78. int i;
79. for (i = 0; i < v->total - 1; i++) {
80. v->items[i] = v->items[i + 1];
81. v->items[i + 1] = NULL;
82. }
83.
84. v->total--;
85.
86. if (v->total > 0 && v->total == v->capacity / 4)
87. vector_resize(v, v->capacity / 2);
88. }
89.
90. void vector_free(vector *v) {
91. free(v->items);
92. }
93.
94. int main(void) {
95. int i;
96.
97. vector v;
98. vector_init(&v);
99.
100. vector_add(&v, "Bonjour");
101. vector_add(&v, "tout");
102. vector_add(&v, "le");
103. vector_add(&v, "monde");
104.
105. for (i = 0; i < vector_total(&v); i++)
106. printf("%s ", (char *) vector_get(&v, i));
107. printf("\n");
108.
109. vector_delete(&v, 3);
110. vector_delete(&v, 2);
111. vector_delete(&v, 1);
112.
113. vector_set(&v, 0, "Hello");
114. vector_add(&v, "World");
115.
116. for (i = 0; i < vector_total(&v); i++)
117. printf("%s ", (char *) vector_get(&v, i));
118. printf("\n");
119.
120. vector_free(&v);
121. }

Output:

$ gcc Vector.c
$ ./a.out

Bonjour tout le monde


Hello World

You might also like