Data Structures and Algorithms | C++ STLs

Data Structures and Algorithms | C++ STLs

In this article, we will be looking at a brief introduction to Data Structures and Algorithms | C++ STLs and some very important STLs like Pairs, Vectors, and Lists.

STL stands for Standard Template Library, this provides four components like Algorithms, Containers, Functions, and Iterators.

Containers – The containers are a type of data structure that is used to store a collection of objects of the same kind under a single variable name.

Algorithms – Algorithms are methods that are applied to the containers. For example, sorting, searching, and transforming.

Iterators – Iterators are used for traversing over the containers in different ways.

Pairs

Pair is one of the most basic container types in the Standard Template Library. A pair stores two values of any type.

Syntax:

pair<datatype, datatype> p = {data,data};

The elements in a pair can be accessed in the following way:

p.first //gives the first element in the pair
p.second //gives the second element in the pair

Let’s look at an example program to understand the usage of pair type.

#include<iostream>
using namespace std;
int main(){
    pair<int,int> p = {1,3};
    cout<<p.first<<endl; //gives the first element in the pair
    cout<<p.second<<endl; //gives the second element in the pair
    return 0;
}
Output:
1
3

We can also use the pair type inside a pair type. Let us look at an example to understand this better.

For example,

#include <iostream>
using namespace std;

int main() 
{
    pair<pair<int,int>, string> p = {{10,20},"String"};
    cout<<p.first.first<<endl;
    cout<<p.first.second<<endl;
    cout<<p.second<<endl;
    return 0;
}
Output:
10
20
String

We can also create an array of pairs. Let us at an example to understand how we can create and access an array of pairs.

#include <iostream>
using namespace std;

int main() 
{
    pair<int,int> arr[] = {{1,2},{3,4},{5,6}};
    for(int i=0;i<3;i++){
      cout<<arr[i].first<<" "<<arr[i].second<<endl;
    }
    return 0;
}

Output:
1 2
3 4
5 6

That is all you need to know about the pair container in the STLs. You’ll gradually learn more when you start using it in problems.

See also  TO CHECK WHETHER THE GIVEN NUMBER IS PRIME NUMBER OR NOT

In the next article, we are going to have a look at Vectors and Lists.

Leave a Comment

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

we provide projects, courses, and other stuff for free. in order for running we use Google ads to make revenue. please disable adblocker to support us.