Vectors In C - JohnHau/mis GitHub Wiki
STL stands for Standard Template Library. STL is a set of general-purpose classes and functions which are mainly used for storing and processing data.
STL can be defined as a library of container classes, algorithms, and iterators. The main idea behind STL is to reuse codes already written and tested. It saves time and effort. STL has four components: Algorithms: It defines a collection of functions specially designed to be used on ranges of elements. Examples are sorting, searching, etc. Containers: Containers store objects and data. There are in total seven standard βfirst-classβ container classes and three container adaptor classes and only seven header files that provide access to these container adaptors. Functions: STL includes classes which overload the function call operator. Instances of such classes are called functors. Iterators: It is used for working upon a sequence of values.It provides generiality in STL. What are Vectors in C++?? Vectors are part of STL. Vectors in C++ are sequence containers representing arrays that can change their size during runtime . They use contiguous storage locations for their elements just as efficiently as in arrays, which means that their elements can also be accessed using offsets on regular pointers to its elements.
Vectors are the dynamic arrays that are used to store data.It is different from arrays which store sequential data and are static in nature, Vectors provide more flexibility to the program. Vectors can adjust their size automatically when an element is inserted or deleted from it.
Vectors are not ordered in C++. Vector elements are placed in adjacent storage and can be easily accessed and traversed across using iterators. In vectors, data is inserted at the end when we use push_back() function . Inserting an element at the end of a vector takes differential time, as sometimes there may be a need of extending the vector, but inserting the element at the beginning or at the middle takes linear time. Removing the last element takes only constant time because no resizing takes place.
Declaration of Vectors in C++: It is mandatory to include #include library before using vectors in C++.
For Vector declaration we need to follow the below syntax:
1 vector< object_type > vector_variable_name; Initialization of Vectors: Pushing the values one-by-one in vector using push_back(): All the elements that need to be stored in the vector are pushed back one-by-one in the vector using the push_back() method. Syntax: 1 vector_name.push_back(element_value); Using the overload constructor of the vector Class: This method is used to populate a vector with multiple times the same value. Syntax: 1 vector<object_type> vector_name (number_of_repetition,element_value); Using Array: This method uses array as a parameter to be passed in the vector constructor. Syntax: 1 vector<object_type> vector_name {val1,val2,val3,....,valn}; Using already initialized vector: This method uses an already created vector to create a new vector with the same values. This method passes the begin() and end() of an already initialized vector.
| Syntax: vector<object_type> vector_name_1{val1,val2,β¦,valn}; vector<object_type> vector_name_2(vector_name_1.begin(),vector_name_1.end())
Various Functions in Vectors are: Iterators:
begin() β It returns an iterator pointing to the first element in the vector. end() β It returns an iterator pointing to the last element in the vector. rbegin() β It returns a reverse iterator pointing to the last element in the vector. rend() β It returns a reverse iterator pointing to the element preceding the first element in the vector. Basically considered as a reverse end. cbegin() β It returns a constant iterator pointing to the first element in the vector. cend() β It returns a constant iterator pointing to the element that follows the last element in the vector. crbegin() β It returns a constant reverse iterator pointing to the last element in the vector. crend() β It returns a constant reverse iterator pointing to the element preceding the first element in the vector. Example Code for Visualizing the use of Iterators:
//C++ Code to Visualize Use of Iterators in C++
#include
#include
using namespace std;
int main()
{
vector a; //Declaration of vector in C++
//Initializing vector βaβ with values from 1 to 7 for (int i = 1; i <=7 ; i++) a.push_back(i);
//Printing the Output of vector βaβ using iterators begin() and end()
cout << "Output of begin and end Function: ";
for (auto i = a.begin(); i != a.end(); ++i)
cout << *i << " ";
//Printing the Output of vector βaβ using iterators cbegin() and cend() cout << "\nOutput of cbegin and cend Function: "; for (auto i = a.cbegin(); i != a.cend(); ++i) cout << *i << " ";
//Printing the output of vector βaβ using iterators rbegin() and rend() cout << "\nOutput of rbegin and rend Function: "; for (auto ir = a.rbegin(); ir != a.rend(); ++ir) cout << *ir << " ";
//Printing the output of vector βaβ using iterators crbegin() and crend()
cout << "\nOutput of crbegin and crend Function: ";
for (auto ir = a.crbegin(); ir != a.crend(); ++ir)
cout << *ir << " ";
return 0;
}
Output:
Example Code for visualizing the use of capacity functions:
//C++ program to demonstrate working of capacity function #include #include using namespace std; int main() { //Declaring vector βaβ of integer type vector a;
//Initializing vector βaβ with values from 1 to 5 for (int i = 1; i <= 5; i++) a.push_back(i);
//Printing size of the vector βaβ
cout << "Size : " << a.size();
//Printing the Capacity of the vector βaβ
cout << "\nCapacity : " << a.capacity();
//Printing the maximum size of the vector βaβ
cout << "\nMax_Size : " << a.max_size();
// resizing the vector βaβ to size 4
a.resize(4);
// printing the vector βaβ size after resize() function
cout << "\nSize : " << a.size();
// checks if the vector is empty or not
if (a.empty() == false)
cout << "\nVector is not empty";
else
cout << "\nVector is empty";
return 0;
} Output:
Modifiers:
assign() β It assigns a new value to the existing elements of the vector. push_back() β It pushes the element from back in the vector. pop_back() β It removes elements from the back of the vector. insert() β It inserts an element before a specified element in the vector. erase() β It is used to remove elements from a specified element or a range in the vector. swap() β It is used to swap the contents of two vectors of the same datatype. The sizes of vectors may differ. clear() β It is used to remove all the elements from the vector. Example code to Visualize the Modifiers Function in vector:
//C++ code to visualize the Modifiers function in vectors #include <bits/stdc++.h> #include using namespace std;
int main() { // Declaring Vector βaβ of integer type vector a;
// filling vector βaβ with 7 in repetition of 4 times
a.assign(4, 7);
//Printing the vector βaβ contents
cout << "The vector contains: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
// inserting 10 to the last position of vector βaβ
a.push_back(10);
int n = a.size();
cout << "\nThe last element is: " << a[n - 1];
// removing the last element from vector βaβ
a.pop_back();
// printing the vector βaβ contents
cout << "\nThe vector contains: ";
for (int i = 0; i < a.size(); i++)
cout << a[i] << " ";
// inserting 3 at the beginning of vector βaβ
a.insert(a.begin(), 3);
//Printing the first element of vector βaβ cout << "\nThe first element is: " << a[0];
// removing the first element
a.erase(a.begin());
//Printing the new first element of vector βaβ cout << "\nThe first element is: " << a[0];
// erasing the vector
a.clear();
//printing the vector βaβ after erasing it
cout << "\nVector size after erase(): " << a.size();
// Creating two vectors βa1β and βa2β of integer type
vector<int> a1, a2;
//Pushing values in vector βa1β and βa2β
a1.push_back(3);
a1.push_back(4);
a2.push_back(5);
a2.push_back(6);
//printing vector βa1β cout << "\n\nVector 1 is: "; for (int i = 0; i < a1.size(); i++) cout << a1[i] << " ";
//printing vector βa2β
cout << "\nVector 2 is: ";
for (int i = 0; i < a2.size(); i++)
cout << a2[i] << " ";
// Swaping vectors βa1β and βa2β
a1.swap(a2);
//Printing vector βa1β after swapping with βa2β cout << "\nAfter Swap \nVector 1 is: "; for (int i = 0; i < a1.size(); i++) cout << a1[i] << " ";
//printing vector βa2β after swapping with βa1β
cout << "\nVector 2 is: ";
for (int i = 0; i < a2.size(); i++)
cout << a2[i] << " ";
return 0;
} Output:
Example code to visualize the Element access function in C++:
#include <bits/stdc++.h> using namespace std;
int main() { //Declaring vector βaβ of integer type vector a;
//pushing values fn vector βaβ from 10 to 100
for (int i = 1; i <= 10; i++)
a.push_back(i * 10);
//Using reference operator to print vector βaβ third element cout << "\nReference operator [g] : a[2] = " << a[2];
//printing element at index 4 of the vector βaβ cout << "\nat : a.at(4) = " << a.at(4);
//printing the front element of vector βaβ cout << "\nfront() : a.front() = " << a.front();
//printing the back element of vector βaβ cout << "\nback() : a.back() = " << a.back();
// pointer to the first element
int* pos = a.data();
//printing the first element of vector using pointer βposβ cout << "\nThe first element is " << *pos; return 0; } Output:
Allocators Function in Vector C++: An allocator is an object that dynamically allocates and deallocates memory. In C++ vectors, there is only one function which can be used as an allocator. This function is called the get_allocator() function. We basically use the get_allocator() to allocate chunks of memory which in return a copy of the allocator object associated with the vector. When to use Vectors? We can use Vectors in the following circumstances:
It is advisable to use vectors when data are consistently changing.
If the size of data is unknown then it is advisable to use vectors.
It is advisable to use vectors when elements are not predefined.
Compared to arrays there are more ways to copy vectors.
Vectors and Array in C++: Vector is a sequential container. Vector is not index based. Array is a fixed-size sequential collection of elements of the same type. Array is index based. Vectors are dynamic in nature. Once the array is initialized itβs size canβt be changed. Vector occupies more memory as compared to array. Array is memory efficient data structure. Accessing time in vectors is more. Array elements are arranged in contiguous memory allocation so it accesses elements in constant time. Vectors can be only declared in C++. Arrays can be declared in any programming language like C, Java, Python, etc. Vector of Vectors in C++ STL: Vector of Vectors is a two-dimensional vector with a variable number of rows where each row is considered as a vector. Each index of vector stores a vector in it. It can be accessed or traversed using iterators. Basically, it can be considered as the array of vectors with dynamic properties. Syntax:
1
- vector<vector<data_type>> vector_name; Example code to visualize Vector of Vectors in C++:
//C++ program to visualize Vector of Vectors #include #include using namespace std;
// Defining the rows and columns of // vector of vectors #define row 3 #define col 3
int main() { // Initializing the vector of vectors vector<vector > a;
// Elements to insert in column
int num = 10;
// Inserting elements into vector
for (int i = 0; i < row; i++) {
// Vector to store column elements
vector<int> a1;
//pushing values in vector βa1β
for (int j = 0; j < col; j++) {
a1.push_back(num);
num += 5;
}
// for creating a 2D vector βaβ pushing 1D vector βa1β into it
a.push_back(a1);
}
// Displaying the 2D vector βaβ
cout<<"2D vector contains:"<<"\n";
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a[i].size(); j++)
cout << a[i][j] << " ";
cout << endl;
}
//Deleting in 2D vector βaβ
a[2].pop_back();
a[1].pop_back();
cout<<"2D vector traversal after deletion:"<<"\n";
//Traversing in 2D vector βaβ using iterator after deletion
for (int i = 0; i < a.size(); i++) {
for (
auto it = a[i].begin();
it != a[i].end(); it++)
cout << *it << " ";
cout << endl;
}
return 0;
} Output: