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:

image

image

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: image

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: image

image

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: image

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: image

image

image

⚠️ **GitHub.com Fallback** ⚠️