Thursday, February 9, 2023
HomeSoftware DevelopmentHigh C++ STL Interview Questions and Solutions

High C++ STL Interview Questions and Solutions


The Customary Template Library (STL) is a set of C++ template courses which can be used to implement extensively in style algorithms and information buildings comparable to vectors, lists, stacks, and queues. It’s a part of the C++ Language ISO customary. STL is a well-liked matter amongst interviewers, so it’s helpful for each freshers and skilled to study the generally requested interview query on STL in C++.

STL Interview Questions

On this article, we’ll see the prime 50 most necessary and most regularly requested interview questions on C++ STL.

STL Interview Questions and Solutions

1. What’s STL?

STL stands for Customary template library and is the gathering of some mostly used algorithms and information buildings comparable to vectors, maps, and so forth. It’s a generalized library that works for all information sorts. STL has 4 elements that are as follows:

components of STL

 

For extra info, consult with the article – STL in C++.

2. What’s a template?

C++ offers a characteristic that permits features and courses to function with generic sorts within the type of templates. We solely have to put in writing the code of a operate or a category as soon as and it will likely be in a position to function on completely different information sorts.

3. Why we use <bits/stdc++.h>?

The <bits/stdc++.h> is a header file that’s used to incorporate all the usual header recordsdata without delay within the C++ program. It’s principally utilized in programming contests to avoid wasting the time required for together with header recordsdata one after the other. However keep in mind that it itself is a non-standard header file of the GNU C++ Library so not all compilers have it.

4. Why do we’d like STL after we can carry out all of the operations utilizing a user-defined information construction and features?

We favor STL over user-defined information construction and features as a result of:

  • It saves time spent writing code for user-defined information buildings.
  • It’s tried, environment friendly, and debugged code examined over a protracted time period.
  • STL is the a part of C++ Language Customary so it’s straightforward to know for different programmers.
  • STL permits us to parameterize the code with the required information kind.

5. What are containers in STL?

The Containers in STL are class templates utilizing which we implement information buildings like a queue, stack, and so forth. These containers act equally to their corresponding information construction, handle the cupboard space for its parts and supply member features to entry them.
For Instance, a Vector acts equally to a dynamic array and has strategies like push_back( ), pop_back( ), dimension( ), and so forth.

Containers are of three sorts:

  • Sequence container
  • Associative container
  • Derived container
types of containers in STL

Completely different Forms of Containers in STL

For extra info, consult with the article –  Containers in STL.

6. What are Algorithms in STL?

Algorithms in STL is a library that accommodates some generally used strategies predefined as operate templates. They typically work on containers taking their iterators as arguments. They’re outlined contained in the <algorithm> header file.

7. What are Functors in STL?

A functor (or operate object) is a C++ class that acts like a operate. Functors are known as utilizing the identical outdated operate known as syntax. To create a functor, we overload the operator( ).

Instance:

MyFunctor(10);
MyFunctor.operator( )(10);       //Each act identical

8. What’s a vector?

A vector is a sort of container that holds the identical properties as a dynamic array. It’s a sequential container during which we will randomly entry any factor utilizing an index quantity however can solely insert or delete parts from the top in fixed time utilizing push_back( ) and pop_back( ) respectively.

Syntax:    

vector<object_name> vector_name;
Vector in C++

Vector in C++

9. What’s an iterator?

An iterator is a variable that factors to a component in an STL container and can be utilized to traverse by means of the weather within the container.

Syntax:

vector<int>::iterator itr;

Right here itr is the iterator that can be utilized for iteration over a vector<int>.

10. What’s the vary by way of vectors?

A variety is a sequence of consecutive parts in a container. The vary could be specified from start( ) to finish( ), containing all the weather of a container.

Vector in C++

 

11. What’s the distinction between an array and a vector?

The variations between an array and a vector in C++ are as follows:

                           Array                           Vector
The array is a sort of knowledge construction. Vector is a sort of Container
Its dimension is fastened after declaration. Vector is dynamically resizeable that may change its dimension when wanted
Parts of an array are saved in stack reminiscence. Parts of the vector are saved within the free retailer.
The dimensions could be obtained by traversing. Dimension could be simply decided utilizing the scale() member operate.
Syntax: data_type  arr_name[size]; Syntax: vector< object_type > identify;
Instance: int arr[5]; Instance: vector<int> arr;

12. How can we insert parts in a vector?

We will insert parts utilizing 4 strategies:

  • Utilizing push_back( ) operate
  • Utilizing insert() operate
  • Utilizing emplace() operate
  • Utilizing [ ] (array subscript)

A. Utilizing push_back():

This technique is used after we need to insert a component on the final place. The dimensions of the vector can be elevated utilizing push_back(). It’s the most used technique of insertion in vectors.

Instance:  

vect.push_back(12);   //right here arr is int vector and 12 is worth inserted.

B. Utilizing insert() operate

We will additionally use the insert() member operate to insert parts in a vector at some specific place.

Instance:

vect.insert(vect.start(), 20);

This may insert the 20 on the index 0 of the vector.

C. Utilizing emplace() operate

We will additionally use the emplace() member operate to insert parts in a vector at some specific place in an analogous method to insert() fuctions.

Instance:

vect.insert(vect.start(), 20);

This may insert the 20 on the index 0 of the vector.

D. Utilizing [ ] (Array Subscript):

If the scale of the vector is predeclared, then we will immediately insert parts utilizing [ ] operators.

Instance:

vect[i] =12;       // worth of ith index can be 12 now.

13. How can we take away parts in a vector?

We will take away parts in vectors utilizing two strategies:

  • Utilizing pop_back() operate
  • Utilizing erase() operate

A. Utilizing pop_back() operate

pop_back() is a member operate of the vector class and it’s used to take away the final factor from the vector.

Instance:

vect.pop_back();   // final factor can be eliminated. 

B. Utilizing erase() operate

erase() can be a member operate of the vector class. It’s used to take away the weather at a specific place within the vector.

Instance:

vect.erase(vect.start() + 2);   // final factor can be eliminated. 

14. What’s the time complexity of insertion and deletion in vector?

Insertion: If the scale of the vector is N, then the time complexity of insertion of a component within the vector is:

  • On the finish: O(1)
  • At M index: O(N – M)

Deletion: If the scale of the vector is N, then the time complexity of deletion of a component within the vector is:

  • On the finish: O(1) 
  • At M index: O(N-M)

15. What’s using auto key phrase in C++?

The auto key phrase specifies that the kind of variable that’s being declared can be mechanically deducted from its initializer. Within the case of features, if their return kind is auto then that can be evaluated by the return kind expression at runtime. Good use of auto is to keep away from lengthy initializations when creating iterators for containers.

16. How can we traverse a vector?

We will traverse in a vector with the next strategies:

  • Utilizing Index
  • Utilizing an Iterator
  • Utilizing auto Key phrase

i) Utilizing index

We will entry the weather of the vector utilizing the index quantity in an analogous method to the arrays.

for (int i = 0; i < v1.dimension(); i++)
{
    cout << v1[i] << " ";
} 

ii) Utilizing an iterator

Iterators are the objects identical to pointers that time to the weather contained in the containers. Iterators are used to iterate over the weather of the containers.

vector<int>::iterator itr;
 
 for (itr = v1.start(); itr < v1.finish(); i++)
 {
     cout << itr << " ";
 }

iii) Utilizing auto

The auto key phrase specifies the kind of variable that’s being declared can be mechanically deducted from its initializer.

for (auto it:v)
{
    cout << it << " ";
}

17. The best way to print vectors in C++?

We will print vectors utilizing a number of methods:

  • Utilizing overloading << Operator
  • Comma separated method
  • Utilizing indexing
  • One line with out  for loop
  • Utilizing (experimental::make_ostream_joiner) with out offering factor kind
  • One line utilizing the lambda operate

For extra info, consult with the article – Print vector in C++.

18. How can we convert the array right into a vector?

There are just a few strategies to covert array right into a vector:

  • Whereas index iteration of array push parts
  • Vary-based Task throughout Initialization
  • Utilizing Inbuilt Operate Insert( )
  • Utilizing Inbuilt Operate Copy( )
  • Utilizing Inbuilt Operate Assign( )
  • Utilizing Inbuilt Operate Rework( )

For extra info, consult with the article – Convert the array right into a vector.

19. How can we convert vectors into arrays?

We will convert the vector into an array utilizing a number of methods:

  • By copying objects one after the other
  • Utilizing STL Algorithm copy()
  • Utilizing STL Algorithm remodel()
  • Utilizing vector::information()

20. The best way to initialize a 2-D vector in C++?

2-D vector could be initialized utilizing a number of strategies:

Syntax:

vector < vector<object_type> > vector_name;

There are some cases like:

i) If we need to insert parts throughout initialization

//v vector containing these values
vector<vector<int>> v={{1,2,3},{4,5,6},{7,8,9}};

ii) If the variety of rows is given:

//rows is the variety of rows
vector<vector<int>> v(rows);

iii) If the variety of rows and columns each are given:

//rows is the variety of rows
//cols is the variety of columns
vector<vector<int>> v(rows, vector<int> (cols));

iv) If all of the values of the vector ought to be initialized by x

//rows is the variety of rows
//cols is the variety of columns
vector<vector<int>> v(rows,vector<int> (cols,x)); 

21. What’s the time complexity of the sorting accomplished in vector utilizing the kind( ) operate?

STL offers the kind( ) operate, which operates with the most effective time complexity potential that may be obtained out of each sorting algorithm. So, the time complexity is O(N logN).

22. What’s using lower_bound() and upper_bound()?

STL algorithms present the performance to search out decrease and higher bounds.

  • A decrease certain of x is the quantity whose worth is a minimum of x.
  • An higher certain of x is the quantity that comes simply after x.

These features are solely efficient when the vector is sorted as a result of they use the binary search algorithm.

Instance:

vector<int> a={2,3,4,5,6,7,8,8,10};

auto x=lower_bound(a.start(),a.finish(),5);
auto y=upper_bound(a.start(),a.finish(),5);

Output:   

*x=5 , *y=6

23. What’s a pair in STL?

Pair is a sort of container that may retailer two parts of the identical or completely different information sorts.

Syntax:

pair<data_type,data_type> pair_name;

Parts of pair could be accessed through the use of first and second key phrases. The primary key phrase is used to entry the primary factor and the second key phrase is used for accessing the second factor.

24. Clarify completely different strategies to insert parts in a pair.

We will insert parts in a pair utilizing 3 ways:

  1. Straight inserting utilizing the primary and second key phrases
  2. Utilizing make_pair() operate
  3. Utilizing { } braces

Contemplate a pair:

pair<int,string> x;

i). Utilizing first and second key phrases

x.first = 1 ;
x.second= "Geeks";

ii). Utilizing make_pair( )

x=make_pair(1,"Geeks");

iii). Utilizing curly brackets

x={1, "Geeks"};

25. During which header file is the std::pair outlined?

The std::pair class is outlined contained in the <utility> header file.

26. What’s a Listing?

A listing is a sort of container in C++ that implements the doubly linked listing information construction. The listing offers non-contiguous storage with solely sequential factor entry i.e we will’t randomly entry any factor utilizing an index quantity.

Syntax:   

listing <object_name> list_name;
List in C++ STL

Listing in C++

27. What’s the time complexity of insertion and deletion within the listing?

Insertion: Suppose the scale of the listing is N, then the time complexity of insertion of a component within the listing is:

  • On the finish:                 O(1)
  • Initially:      O(1)
  • At M index:                O(M)

Deletion: Suppose the scale of the listing is N, then the time complexity of deletion of a component within the listing is:

  • On the finish:                 O(1)
  • Initially:      O(1)
  • At M index:                O(M)

28. Distinction between a vector and an inventory?

Vector

Listing

Insertion on the finish requires fixed time however insertion elsewhere is dear. Insertion is reasonable irrespective of the place within the listing it happens as soon as the factor is discovered.
Random entry to parts is feasible. Random entry to parts is just not potential.
It has contiguous reminiscence.  Whereas it has non-contiguous reminiscence.
A vector could have a default dimension. The listing doesn’t have a default dimension.
Iterators change into invalid if parts are added to or faraway from the vector. Iterators are legitimate if parts are added to or faraway from the listing.
Syntax: vector<data_type> vector_name; Syntax: listing<data_type> list_name;

For extra info, consult with the article – Vector vs Listing.

29. How can we take away parts from the listing?

There are just a few strategies to take away parts from the listing:

  • Utilizing listing::erase()
  • Utilizing listing::pop_front() and listing::pop_back()
  • Utilizing take away() and remove_if()

For extra info, consult with the article – Take away parts from the listing.

30. What’s a stack?

Stack in C++ STL

 

A stack is a container adapter that implements the stack information construction in STL. It has the next properties:

  1. Parts comply with the LIFO (Final In First Out) order of operation.
  2. Solely the factor on the prime could be accessed.
  3. Insertion and Elimination could be accomplished solely from the highest.

Syntax:

stack <data_type> identify;

Instance: Chairs put one above the opposite so we will now both put,  take away or entry the chair on the prime.

31. What are the essential features related to the STL stack?

The fundamental features related to the STL stack are as follows:

  • push(): This operate is used for inserting parts on the prime of the stack.
  • pop(): The pop() operate is used for eradicating parts from the highest.
  • dimension(): It returns the scale of the stack.
  • prime(): The highest() operate returns the highest factor of the stack.
  • empty(): It checks if the stack is empty or not.

32. What’s the time complexity of insertion and deletion within the stack?

Insertion and Deletion are solely potential on the finish of the container with the time complexity of O(1). At another place if you wish to insert a component then we have to use one other container or can use one other stack, copy the factor and take away it from the principle stack then push the factor at that place after then we have to push all parts once more.

So, including or eradicating on the M place we have to take away N-M parts after which add them once more so, O(2*(N-M)) approx O(N).

33. What’s a queue in STL?

Queue in STL

 

A queue in C++ STL is a container adapter that implements the queue information construction. It has the next properties:

  • Follows FIFO ( First In First Out) order of operation
  • Queue permits insertion from one facet and elimination from one other facet.
  • Insertion and elimination each take O(1) time complexity.
  • Solely the factor on the entrance is accessible.

Syntax:

queue <data_type> identify;

34. What are the generally used member features of the STL Queue?

Some generally used features related to queue:

  • push( x ): It’s used to insert x within the queue.
  • pop( ): Removes the least current factor from the listing i.e. factor on the entrance.
  • entrance( ): It’s used for accessing the entrance factor.
  • dimension( ): This operate returns the scale of the queue.

35. What’s a deque?

STL Deque in C++

 

Deque is also called a Double-ended queue. Deque is a sort of container that may insert and take away parts from each ends. It might push utilizing push_back( ) and push_front( ) for inserting parts from the front and back respectively and may take away utilizing pop_back( ) and pop_front( ) for eradicating parts from the front and back respectively.

Syntax:

deque <object_type> deque_name;

36. What’s the time complexity of insertion and deletion within the deque?

Insertion and Elimination of parts are potential from each side of the deque, each insertion and deletion take O(1) time complexity from both facet.

For inserting parts at index M someplace contained in the deque, the time complexity can be linear i.e O(N).

36. What’s a set in STL?

A set is a sort of associative container which shops worth in a sorted manner with out duplication. It’s sorted in rising order by default.

Syntax:

set <object_type> identify;

The set is applied on a Binary Search Tree (usually red-black tree), due to which era complexity of the weather which can be saved in sorted type has the complexity of insertion, discover and elimination is O(log N)

For extra info, consult with the article – Set in C++.

37. How can we alter the sorting order of a set?

Within the set, all the weather saved are sorted in rising order, however we will change the sorting order of the set to reducing through the use of a better<int> (STL functor) as a comparator within the set declaration.

Syntax:

set <data_type, better<data_type>> identify;

Equally, we will use any comparator operate, functors, or lambda expressions rather than better<int> for customized sorting order.

38. The best way to entry parts in a set by index?

We will entry the factor on the Nth index in a set by: 

  • Utilizing Iterator
  • Utilizing std::advance() technique
  • Utilizing std::subsequent() technique

To know extra about these strategies, please consult with this text – The best way to Entry Parts in Set by Index in C++?

39. The best way to iterate over the set?

We will iterate over the STL set utilizing the next strategies:

  • Iterate over a set utilizing an iterator.
  • Iterate over a set in a backward path utilizing reverse_iterator.
  • Iterate over a set utilizing a range-based for loop.
  • Iterate over a set utilizing for_each loop.

For extra info, consult with the article –  Iterate over the set.

40. What’s a multiset in STL?

A multiset is an associative container that acts the identical manner as a set however permits duplicate values.

Syntax:

multiset<object_type> identify;

The multiset can be applied utilizing Binary Search Tree. The time complexity of the weather saved in sorted type has the complexity of insertion, discover and elimination is O(log N).

For extra info, consult with the article – Multiset in C++. 

41. What’s a unordered_set?

The unordered_set is an unordered associative container that shops values in an unsorted manner with out duplication.

Syntax:

unordered_set <object_type> identify;

The unordered_set is applied utilizing the Hash desk information construction. The time complexity of the weather saved in sorted type has the complexity of insertion, discover and elimination is O(1) for common instances and O(n) time within the worst case.

For extra info, consult with the article – unordered_set in C++.

42. What’s a unordered_multiset in STL?

The unordered_multiset is an unordered associative container that shops values in unsorted manner and permits duplicate values.

Syntax:

unordered_multiset <object_type> identify;

The unordered_multiset relies on the Hash-table information construction. The time complexity of the weather saved in sorted type has the complexity of insertion, discover and elimination is O(1) for common instances and O(n) for the worst case.

For extra info, consult with the article – unordered_multiset in C++.

43. What’s a map?

The map in STL is an associative container that shops the info within the type of key-value pairs. It’s sorted in keeping with keys and every secret’s distinctive.

Syntax:

map <object_type> identify;

The map is mostly applied on the Purple-Black Tree (Self Balancing B.S.T.) information construction. The time complexity for search, insert and delete operations is O(logN), the place N is the variety of key-value pairs within the map.

For extra info, consult with the article – Map in C++.

44. What’s a multimap?

A Multimap is a sort of associative container that’s much like a map i.e storing key-value pairs and sorting in keeping with keys, however the distinction is that there could be a number of values related to a single key.

Syntax:

multimap <object_type> identify;

The multimap can be based mostly on the Balanced Binary Tree information construction. The time complexity of the search, insert, and delete operations is logarithmic i.e. O(logN).

For extra info, consult with the article – Multimap in C++.

45. What’s a unordered_map?

An unordered_map is a sort of unordered associative container that’s much like a map however the values should not sorted in any order.

Syntax:

unordered_map <object_type> identify;

The unordered_map relies on the Hash Desk. The time complexity of the insert, delete, and search operations is O(1) for common instances and O(N) for the worst case.

For extra info, consult with the article – unordered_map in C++.

46. What’s a unordered_multimap?

An unordered_multimap can be an unordered container that shops key-value pairs in an unsorted manner. We will map a number of values to the identical key on this container.

Syntax:

unordered_multimap <object_type> identify;

The unordered_multimap relies on the Hash Desk. The time complexity of the weather which can be saved in sorted type has the complexity of insertion, discover and elimination is O(1) common time and O(n) worst time.

For extra info, consult with the article – unordered_multimap in C++.

47. What’s priority_queue?

A priority_queue is a container adapter that’s used to create a queue whose order of operation relies on the precedence of the factor. The upper precedence factor will come out first as an alternative of the least current one.

It’s applied utilizing heap information buildings in C++.

Syntax:

priority_queue < object_type > heap_name;

By default, this can create a max-heap during which the most important key will pop first. For extra info, consult with the article – Priority_queue in C++.

48. The best way to create a min-heap utilizing STL priority_queue?

We will create a min-heap utilizing priority_queue by the next technique:

Syntax for Min heap:

priority_queue < object_type , vector<object_type> , better<object_type> > heap_name;

The third argument is the comparator operate or functor with a boolean return kind. We have now used better<> which is a built-in functor of STL for evaluating two values to test which one is larger.

One other method to create a min-heap utilizing priority_queue is to only multiply the keys by -1 earlier than inserting them into the queue.

49. What are the essential operations on priority_queue in C++?

The fundamental operations that may be carried out on the priority_queue are as follows:

  • push( ): used for insertion of the factor
  • pop( ):  used for eradicating prime factor
  • prime( ): used for checking both min for min-heap and max for max-heap.
  • dimension( ): used for getting the scale of the heap.

We will solely entry a prime factor of the heap.

50. How is priority_queue applied in C++ STL ? What’s the time complexity of fundamental operations in it?

The priority_queue is applied as a heap information construction in C++. As heap is applied utilizing an array, the priority_queue in STL can be applied utilizing STL vectors that are nothing however dynamic arrays.

The time complexity of fundamental operations in priority_queue is as follows:

  • push( ): O(logN)
  • pop( ):  O(1)
  • prime( ): O(1)
  • dimension( ): O(1)

Bouns Questions

1. Write code to iterate from the primary factor to the final factor when the vector is given

void iter(vector<int> v)
{
    vector<int>::iterator it1,it2;
    
    for(it1=v.start(),it2=v.finish(),it2;it1!=it2;it1++)
    {
        cout<<*it1<<" ";
    }   
    
    cout<<endl;
}

 2. Write code to type and reverse the vector.

vector<int> sortVector(vector<int> v)
{
    type(v.start(), v.finish());
    return v;
}

vector<int> reverseVector(vector<int> v)
{
    for(int i = 0, j = v.dimension() - 1; i < j; i++, j--)
        swap(v[i],v[j]);

    return v;
}

4. Declare, Insert and Print a pair of strings paired with one other pair of int paired with int.

//Declaration of Pair
pair<string,pair<int,int>> x;

//Inserting factor
x= { "Geeks" , { 1, 2} };

//Printing factor
cout<<x.first<<" "<<x.second.first<<" "<<x.second.second;

5. Discover the index of a given factor in a vector, such that the subsequent factor to it’s 2, and if there exists multiple such index returns the bigger one if there is no such thing as a such index then return -1.

int find_index(vector<int> &V,int a)
{
    stack<int> temp;
    
    for(int i=0;i<V.dimension();i++)
    {
        if(V[i]==a){
            temp.push(i);
        }
        
        if(i==temp.prime()+1){
            if(V[i]==2)
                proceed;
            else if(V[i]==a){
                temp.pop();
                temp.push(i);
            }
            else{
                temp.pop();
            }
        }
    }
    
    if(temp.prime()==V.dimension()-1)
        temp.pop();

    if(temp.dimension()==0)
        return -1;
        
    return temp.prime();
}

6. Write a Class stack to implement a stack utilizing a queue.

class Stack {
    queue<int> q1, q2;
 
public:
    void push(int x)
    {
        q2.push(x);
        
        whereas (!q1.empty()) {
            q2.push(q1.entrance());
            q1.pop();
        }
 
        queue<int> q = q1;
        q1 = q2;
        q2 = q;
    }
 
    void pop()
    {
        if (q1.empty())
            return;
        q1.pop();
    }
 
    int prime()
    {
        if (q1.empty())
            return -1;
        return q1.entrance();
    }
 
    int dimension()
    {
        return q1.dimension();
    }
};

7. Write a code to carry out push from the again, pop from the entrance, get the scale, get again and get entrance operations.

void push(queue<int> &q,int x)
{
    q.push_back(x);
}

int pop(queue<int> &q)
{
    int x=getFront(q);
    q.pop_front();
    
    return x;
}


int getSize(queue<int> &q)
{
    return q.dimension();
}

int getBack(queue<int> &q)
{
    return q.again();
}

int getFront(queue<int> &q)
{
    return q.entrance();
}

8. Write a code to test duplicate values within the vector and print them with the absolute best time complexity.

void dupicate(vector<int> &V)
{
    unordered_set<int> retailer;
    
    for(auto it:V)
    {
        if(retailer.discover(it)!=retailer.finish())
        {
            cout<<it<<" ";
        }
        else
        {
            retailer.insert(it);
        }
    }
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments