C Vector: Write And Explain Vector With Program In C - JohnHau/mis GitHub Wiki

C++ Vector is a template class that is a perfect replacement for the right old C-style arrays. It allows the same natural syntax used with plain arrays. Still, it offers a series of services that free the C++ programmer from taking care of the allocated memory and consistently operating on the contained objects.

C++ STL The C++ STL (Standard Template Library) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks.

C++ Vector C++ Vector is a sequence of containers that can be changed dynamically. This means you can change its size any time you want. Like an array, it also takes contiguous memory location, but the difference is Vector is dynamic where Array is not.

The first step using a vector is to include the appropriate header.

#include Note that the header file name does not have any extension; this is true for all Standard Library header files. The second thing to know is that all of the Standard Library lives in the namespace std. This means that you have to resolve the names by prepending std:: to them.

Header File Before using a vector, you have to include the header file vector. See the below code.

#include #include int main() { return 0; } You can bring the entire namespace std into scope by inserting a using directive on top of your cpp file.

image

image

image

image

image

vector::erase() It erases the element from the vector. The erase() function is used to remove the element from specified positions. Elements are removed from the specified position of the container.

Syntax vector.erase(startpos, endpos) It has either startpos or endpos parameters or only the startpos parameter.

image

vector::emplace() The vector::emplace() is the STL in C++, which extends the container by inserting the new element at the position. Reallocation happens only if there is a need for more space. Here the container size increases by one. Finally, it constructs and inserts the element in the vector.

Syntax template <class... Args> iterator emplace (iterator_position, Args&&... args); The function accepts two mandatory parameters, which are specified below.

iterator_position – It specifies the iterator pointing to the position in the container where the new element is to be inserted. args – It specifies the element to be inserted in the vector container.

image

C++ Vector Modifiers Example See the following code example of C++ Vector Modifiers.

#include<bits/stdc++.h> #include using namespace std; int main() { vectorv1; //assign the vector with 5 times 50 v1.assign(5,50); cout<<"After assign the vector is: "; for(int i=0;i<v1.size();i++) { //v1.size() will return size of vector cout<<v1[i]<<" "; } cout<<"\n"; //====================================================================================//

//insert 100 at the last of the vector
//using push_back()
v1.push_back(100);
int n=v1.size();
cout<<"The last element of the vector right now is: "<<v1[n-1]<<" and size: "<<n<<"\n";

//====================================================================================//

//delete the last element of the vector
//using pop_back()
v1.pop_back();
n=v1.size();
cout<<"After removing the size of vector is "<<n<<" & last element is "<<v1[n-1]<<"\n";

//====================================================================================//

//insert 70 at the front of the vector
//using insert()
v1.insert(v1.begin(),70);
cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";

//======================================================================================//

//remove the first element using erase
v1.erase(v1.begin());
cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";

//=====================================================================================//

//swap first and last element of the vector
//using swap()
n=v1.size();
cout<<"Before swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n";
swap(v1[0],v1[n-1]);
cout<<"After swapping the fisrt value is "<<v1[0]<<" last value: "<<v1[n-1]<<"\n";

//======================================================================================//

//insert element at front using emplace()
v1.emplace(v1.begin(),12);
v1.emplace(v1.begin(),12);
cout<<"After inserting at begining the front value is: "<<v1[0]<<"\n";

//=======================================================================================//

//insert element at the back of the vector
//using emplace_back()
v1.emplace_back(60);
n=v1.size();
cout<<"After inserting at back of the back value is: "<<v1[n-1]<<"\n";

//========================================================================================//

//clear all the element of the vector
v1.clear();
n=v1.size();
cout<<"After clearing the size of vector is: "<<n<<"\n";

//================================================================================================//
return 0;

} The output is the following.

image

Here one thing to note that emplace() and emplace_back() works on c++11 or above. So if your version is lower, then it might not work.

image

image

image

image

Vector Iterators Example See the following iterators example in C++ Vector.

#include #include using namespace std; int main() {

//First insert some element to the vector
vector<int> v1;
int n,x;
cout<<"Enter the size of the vector: ";
cin>>n;
cout<<"Enter vector values:\n";
for (int j=0;j<n;j++)
{
    cin>>x;
    v1.push_back(x);
} 
//================Print all element using begin() & end()==========================//
cout<<"Output of all elements using begin() & end(): "; 
for (auto i =v1.begin(); i!=v1.end();++i) 
    cout<<*i<<" "; 

//=====================Print all element using cbegin() & cend()======================// cout<<"\nOutput of all elements using cbegin and cend: "; for (auto i=v1.cbegin();i!=v1.cend(); ++i) cout<<*i<<" ";

//====================Print all element using crbegin() & crend()===================// cout<<"\nOutput of all elements using crbegin and crend: "; for (auto i=v1.crbegin();i!=v1.crend();++i) cout<<*i<<" "; //=====================Print all element using rbegin() & rend()==========================// cout<<"\nOutput of all elements using rbegin and rend: "; for (auto i=v1.rbegin();i!=v1.rend();++i) cout<<*i<<" "; //========================================================================================// return 0; } The output is the following.

image

image

image

image

Vector Iterator Program in C++ #include #include using namespace std; int main() { //First insert some element to the vector vector v1; int n,x; cout<<"Enter the size of the vector: "; cin>>n; cout<<"Enter vector values:\n"; for (int j=0;j<n;j++) { cin>>x; v1.push_back(x); } //=======================Demonstrate size()===============================//

cout<<"Size of the vector is: "<<v1.size()<<"\n";

//======================Demonstrate max_size()=======================================// 

cout<<"\nMax_Size of the vector is: "<<v1.max_size(); 

//======================Demonstrate capacity()======================================//

cout<<"\nCapacity of the vector is: "<<v1.capacity();

//======================Resize the vector to n-2===================================//

v1.resize(n-2);  
cout<<"\nAfter resize the Size of the vector is: "<<v1.size(); 

//=====================Demonstrate reserve() =====================================//
cout<<"\nBefore reserve the size of the vector is: "<<v1.size();
cout<<"\nBefore reserve the capacity of the vector is: "<<v1.capacity();
v1.reserve(40);
cout<<"\nAfter reserve the capacity of the vector is: "<<v1.capacity();
cout<<"\nAfter reserve the size of the vector is: "<<v1.size();
//======================Shrink the vector==========================================//
v1.shrink_to_fit(); 
cout << "\nVector elements are: "; 
for (auto i=v1.begin();i!=v1.end();i++) 
    cout<<*i<<" "; 
//=====================Clear all elements and check if the vector is empty================//
v1.clear();
if (v1.empty() == false) 
    cout<<"\nVector is not empty"; 
else
    cout<<"\nVector is empty";
//============================================================================================//
return 0; 

} The output is the following. image

image

image

image

#include #include using namespace std; int main() { //==================First insert some element to the vector==========================// vectorv1; int n,x; cout<<"Enter the size of the vector: "; cin>>n; cout<<"Enter vector values:\n"; for (int j=0;j<n;j++) { cin>>x; v1.push_back(x); } //================== Show value at position 2 using Reference Operator ==============//

cout<<"\nReference operator v1[2]= "<<v1[2]; 

//================== Show value at position 3 using at() =======================//

cout<<"\nValue at position 3 is: "<<v1.at(3); 

//===================Show the first element of the vector========================//
cout <<"\nFirst element of the vector is: "<<v1.front(); 

//================Show the last element of the vector===========================//
cout << "\nLast element of the vector is: "<<v1.back(); 

//================Showing all the elements  using data==========================// 
int* i=v1.data();
cout<<"\nAll the elements of the vector is:\n";
for(int j=0;j<v1.size();j++)
{
    cout<<*i++<<" ";
}
return 0; 

} The output of the above C++ program is following.

image

Conclusively, C++ Vector Example is over.

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