What Are the Questions Asked in A C++ Interview
Question: What is the Standard Template Library (STL) in C++?
Answer:
The Standard Template Library (STL) is a powerful library in C++ that provides a set of generic classes and functions designed to help with common data structures and algorithms. It allows programmers to efficiently manage collections of data and perform operations like searching, sorting, and manipulating data without having to implement these functionalities from scratch.
The STL is built around the concepts of generic programming, where algorithms and data structures are written independently of the specific data types they operate on. This is achieved by using templates, which allow the creation of classes and functions that work with any data type.
Key Components of the STL:
The STL consists of four main components:
-
Containers: These are data structures used to store collections of data. There are several types of containers in STL, each optimized for specific use cases.
-
Algorithms: STL provides a large collection of built-in algorithms for operations like sorting, searching, modifying, and manipulating data within containers.
-
Iterators: Iterators are objects that allow traversal of container elements. They provide a unified way to access data in containers, independent of the container type.
-
Functors (Function Objects): Functors are objects that can be called as if they were functions. They are often used as arguments to algorithms to customize the behavior of the algorithm.
1. Containers in STL:
STL containers are designed to hold data in different forms. The major types of containers are:
-
Sequence Containers:
- Vector: A dynamic array that can resize itself when needed. It provides fast random access and efficient insertion/removal of elements at the end.
- Deque: A double-ended queue that allows insertion/removal of elements from both ends in constant time.
- List: A doubly linked list that allows efficient insertion/removal of elements anywhere in the list.
- Array: A fixed-size array, which is similar to a C++ array but provides additional utility functions and type safety.
- Forward List: A singly linked list (available since C++11), optimized for situations where only forward traversal is needed.
-
Associative Containers:
- Set: A collection of unique elements, typically implemented as a balanced binary tree (e.g., red-black tree). The elements are always sorted.
- Map: A collection of key-value pairs, where each key is unique. Keys are automatically sorted.
- Multiset: Similar to
set
, but allows duplicate elements. - Multimap: Similar to
map
, but allows multiple pairs with the same key.
-
Unordered Containers (since C++11):
- Unordered Set: A set implemented using a hash table. It provides faster access to elements but does not maintain order.
- Unordered Map: Similar to
map
, but uses a hash table for storing key-value pairs. It offers faster lookup times thanmap
. - Unordered Multiset: Similar to
unordered_set
, but allows duplicate elements. - Unordered Multimap: Similar to
unordered_map
, but allows multiple pairs with the same key.
2. Algorithms in STL:
The STL provides a wide range of built-in algorithms that operate on containers via iterators. These include:
- Sorting Algorithms:
sort()
,stable_sort()
,partial_sort()
,nth_element()
- Searching Algorithms:
find()
,binary_search()
,lower_bound()
,upper_bound()
- Modification Algorithms:
copy()
,fill()
,transform()
,remove()
- Non-modifying Algorithms:
for_each()
,count()
,equal()
,reverse()
- Set Operations:
union()
,intersection()
,difference()
- Numeric Algorithms:
accumulate()
,inner_product()
,partial_sum()
These algorithms provide a high level of abstraction and can be applied to various containers.
3. Iterators in STL:
Iterators in STL are used to traverse through containers and allow algorithms to work independently of the underlying container types. The different types of iterators are:
- Input Iterator: Allows reading of elements in a container (e.g.,
std::istream_iterator
). - Output Iterator: Allows writing to a container (e.g.,
std::ostream_iterator
). - Forward Iterator: Allows both reading and writing, and can only move forward.
- Bidirectional Iterator: Allows movement in both directions (forward and backward).
- Random Access Iterator: Supports moving forward, backward, and direct access to any element (e.g., iterating over a
vector
).
4. Functors in STL:
A functor is an object that can be called like a function. In STL, functors are often used to define the behavior of certain algorithms (such as comparison or transformation).
For example, a comparator functor can be used with std::sort()
to define a custom sorting order:
#include <iostream>
#include <vector>
#include <algorithm>
class Compare {
public:
bool operator()(int a, int b) const {
return a < b; // Custom comparison (ascending order)
}
};
int main() {
std::vector<int> v = {5, 3, 8, 1, 4};
std::sort(v.begin(), v.end(), Compare());
for (int num : v) {
std::cout << num << " ";
}
return 0;
}
Example of Using STL:
Here is an example of using a vector container and the sort
algorithm from STL:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Create a vector and add elements to it
std::vector<int> vec = {4, 1, 3, 2, 5};
// Use the sort algorithm from STL to sort the vector
std::sort(vec.begin(), vec.end());
// Print sorted vector
for (int i : vec) {
std::cout << i << " ";
}
return 0;
}
Output:
1 2 3 4 5
In this example, std::vector<int>
is a container, and std::sort()
is an algorithm. The iterator vec.begin()
points to the first element of the vector, and vec.end()
points one past the last element.
Advantages of STL:
- Efficiency: STL containers and algorithms are highly optimized for performance.
- Generic Programming: The use of templates allows algorithms to work on a wide range of container types and data types.
- Reusability: The STL provides a well-designed, reusable set of data structures and algorithms.
- Ease of Use: STL provides intuitive interfaces for working with data structures and algorithms.
Summary:
The Standard Template Library (STL) is a collection of generic classes and functions in C++ that provide common data structures (like vectors, lists, sets, and maps) and algorithms (like sorting, searching, and modifying). By using templates, STL allows developers to write efficient and reusable code for handling different types of data in a consistent manner. The key components of STL—containers, algorithms, iterators, and functors—work together to enable high-level operations while maintaining performance and flexibility.
Question: What is ::
(Scope Resolution Operator) in C++?
Answer:
The ::
(scope resolution operator) in C++ is used to define the scope of variables, functions, and classes. It allows you to access members (variables or functions) of a class, namespace, or other scope outside of the current scope. It is a way to clarify which scope a particular entity belongs to, especially when there are name conflicts.
Here are the common uses of the scope resolution operator (::
):
1. Accessing Global Variables
If you have a variable or function with the same name inside a function, class, or namespace, you can use ::
to refer to the global variable or function.
#include <iostream>
int value = 10; // Global variable
void display() {
int value = 20; // Local variable
std::cout << "Local value: " << value << std::endl;
std::cout << "Global value: " << ::value << std::endl; // Access global 'value'
}
int main() {
display();
return 0;
}
Output:
Local value: 20
Global value: 10
In the example above, the scope resolution operator ::
is used to access the global value
variable, overriding the local value
variable inside the display()
function.
2. Accessing Class Members (Static Members)
You can use ::
to access static members of a class. Static members are shared by all instances of the class and can be accessed without an object of the class.
#include <iostream>
class MyClass {
public:
static int count; // Static variable
MyClass() {
count++;
}
static void displayCount() { // Static function
std::cout << "Count: " << count << std::endl;
}
};
int MyClass::count = 0; // Definition of static member
int main() {
MyClass obj1, obj2;
MyClass::displayCount(); // Access static function using scope resolution
return 0;
}
Output:
Count: 2
In this example, the ::
operator is used to access the static function displayCount()
and the static variable count
of the class MyClass
.
3. Defining Member Functions Outside the Class
If a class member function is defined outside the class, the scope resolution operator is used to associate the function definition with the class.
#include <iostream>
class MyClass {
public:
void show(); // Declaration
};
void MyClass::show() { // Definition outside the class
std::cout << "Hello from MyClass!" << std::endl;
}
int main() {
MyClass obj;
obj.show(); // Calling the function
return 0;
}
Output:
Hello from MyClass!
Here, the ::
operator is used to define the show()
function outside the class MyClass
.
4. Accessing Members of a Namespace
You can use the ::
operator to access members (variables, functions, or classes) within a namespace.
#include <iostream>
namespace MyNamespace {
int value = 100;
void display() {
std::cout << "Value in MyNamespace: " << value << std::endl;
}
}
int main() {
MyNamespace::display(); // Access function in MyNamespace
std::cout << "Value: " << MyNamespace::value << std::endl; // Access variable in MyNamespace
return 0;
}
Output:
Value in MyNamespace: 100
Value: 100
In this example, ::
is used to access the variable value
and the function display()
inside the MyNamespace
.
5. Defining a Function Outside a Class (Even in Derived Classes)
You can also use ::
to define or refer to a function outside the class in the case of inheritance.
#include <iostream>
class Base {
public:
virtual void display() {
std::cout << "Base class display" << std::endl;
}
};
class Derived : public Base {
public:
void display() override {
std::cout << "Derived class display" << std::endl;
}
};
int main() {
Base* basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->display(); // Calls Derived class function due to polymorphism
derivedObj.Base::display(); // Using scope resolution to call Base class function
return 0;
}
Output:
Derived class display
Base class display
In the example above, Base::display()
is called explicitly using the scope resolution operator from the Derived
class object, which would normally call the overridden display()
method.
Summary:
The scope resolution operator (::
) in C++ is used for:
- Accessing global variables and functions when there are naming conflicts with local ones.
- Accessing static members of a class (variables or methods).
- Defining member functions outside the class.
- Accessing members of a specific namespace.
- Calling base class methods from a derived class, especially in case of function overriding.
It provides a way to explicitly specify which scope (global, class, or namespace) you are referring to, helping to resolve name conflicts and enabling clear and efficient code.
Read More
If you can’t get enough from this article, Aihirely has plenty more related information, such as C++ interview questions, C++ interview experiences, and details about various C++ job positions. Click here to check it out.
Tags
- C++
- C++ interview questions
- C++ constructors
- Inline keyword
- Reference in C++
- Class and object in C++
- Call by value vs call by reference
- Abstract class
- Virtual functions
- New vs malloc
- This pointer in C++
- C++ templates
- C++ struct vs class
- Exception handling in C++
- Operator overloading in C++
- Polymorphism in C++
- C++ pointers
- C++ iterators
- C++ STL
- Scope resolution operator
- C++ memory management
- C++ exception handling
- C++ overloading
- C++ function overriding