In this guide, we will explore the top 10 commonly utilized built-in C++ functions for Competitive Programming.
Introduction of Inbuilt C++ Functions
In C++, built-in functionalities are commonly referred to as standard library features or functionalities provided through the C++ Standard Template Library (STL). These functionalities encompass a wide range of tasks and functions, simplifying the process for developers to execute complex operations without the need to develop them from the beginning.
Key factors of in-built features in C++:
Here are some primary aspects about built-in functionalities in C++:
- Standard Library (STL):
The C++ Standard Library consists of pre-built modules and functions that provide advanced functionality. It forms an integral part of the C++ programming language and is accessible to all C++ applications.
- Header Files:
If you plan to utilize those functionalities, you need to include the appropriate header files in your program. For instance, the header provides functionalities for input and output operations, supports dynamic arrays, and offers various algorithms.
- Namespace:
Most of the standard functionalities are detailed within the std::namespace. This namespace provides a scope for defining identifiers such as functions, variables, and classes.
Common Inbuilt Functions:
There are several common in-built functions in C++. Some main common in-built functions are as follows:
- Input/Output: Functions like cin and cout for console enter and output.
- Containers: Functions for running with bins like vectors, arrays, lists, etc.
- Algorithms: Sorting (sort), searching (find), and different algorithms.
- String Handling: Functions for string manipulation (length, substr, etc.).
- Mathematics: Mathematical features which include sqrt, sin, cos , etc.
- Memory Management: Functions like new and delete for dynamic reminiscence allocation.
Top 10 most used in-built C++ functions for competitive programming
In competitive programming, developers often rely on a set of commonly utilized C++ functionalities from the Standard Template Library (STL) to effectively address challenges. Below is a compilation of 10 frequently employed built-in functions in C++ for competitive programming:
1. Input/ Output function in C++:
In C++, input and output operations typically involve utilizing the header file, which provides the "cin" and "cout" objects for reading from and writing to the standard input and output streams.
Example:
#include <iostream>
int main() {
int x;
std::cout << "Enter a number: ";
std::cin >> x;
std::cout << "You entered: " << x << std::endl;
return 0;
}
Output:
Enter a number: [User input]
You entered: [The value entered by the user]
2. Vector function ("vector")
In C++, vectors are an integral component of the Standard Template Library (STL) and provide a dynamic array structure. They are highly versatile and widely employed for various programming purposes. Below are some commonly utilized functionalities and actions with vectors in C++:
#include <vector>
std::vector<int> numbers = {1, 2, 3, 4, 5};#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// Print the elements of the vector
std::cout << "Elements of the vector: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Output:
Elements of the vector: 1 2 3 4 5
3. Sorting function ("sort")
In C++, the sort function is included in the <algorithm> header and is employed to arrange the elements of a collection in ascending order by default. Here's an example demonstrating how to utilize the sort function:
#include <algorithm>
std::sort(v.begin(), v.end());
4. Searching function:
In C++, the header provides a variety of functionalities for examining elements within a sequence. Two commonly utilized searching functions are std::find and std::binary_search.
Example:
#include <algorithm>
if (std::binary_search(v.begin(), v.end(), 3)) {
// Element found
}
auto it = std::find(v.begin(), v.end(), 2);
5. Pair Function
In C++, the std::pair template class found in the header allows you to group different types of elements together. It is commonly utilized to represent a pair of values. Below is a simple illustration showcasing the usage of std::pair:
Example:
#include <iostream>
#include <utility> // Include the <utility> header for std::pair
int main() {
// Create a pair of integers
std::pair<int, int> coordinates = std::make_pair(3, 5);
// Access elements of the pair
int x = coordinates.first;
int y = coordinates.second;
// Print the pair values
std::cout << "Coordinates: (" << x << ", " << y << ")" << std::endl;
return 0;
}
Output:
Coordinates: (3, 5)
6. Maps
In C++, the Standard Template Library (STL) provides a map container that serves as an associative container. It stores key-value pairs and allows efficient retrieval of values based on their corresponding keys. Here is a brief overview of how to utilize std::map in C++:
Example:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> studentMap = {
{101, "John"},
{102, "Alice"},
{103, "Bob"}
};
// Accessing elements
std::cout << "Student 102: " << studentMap[102] << std::endl;
// Iterating through the map
for (const auto& pair : studentMap) {
std::cout << "ID: " << pair.first << ", Name: " << pair.second << std::endl;
}
return 0;
}
Output:
Student 102: Alice
ID: 101, Name: John
ID: 102, Name: Alice
ID: 103, Name: Bob
7. Sets
In C++, the std::set is a widely recognized component of the standard template library (STL) that serves as a sorted associative container holding unique elements. Below is a sample program showcasing the utilization of std::set:
Example:
#include <iostream>
#include <set>
int main() {
// Declare and initialize a set of integers
std::set<int> mySet = {30, 10, 50, 20, 40, 30};
// Print elements in the set
std::cout << "Elements in the set:";
for (const auto& element : mySet) {
std::cout << " " << element;
}
std::cout << std::endl;
// Check if an element is present in the set
int searchElement = 20;
if (mySet.find(searchElement) != mySet.end()) {
std::cout << searchElement << " is present in the set." << std::endl;
} else {
std::cout << searchElement << " is not present in the set." << std::endl;
}
// Erase an element from the set
mySet.erase(30);
// Print the set after erasing an element
std::cout << "Elements in the set after erasing 30:";
for (const auto& element : mySet) {
std::cout << " " << element;
}
std::cout << std::endl;
return 0;
}
Output:
Elements in the set: 10 20 30 40 50
20 is present in the set.
Elements in the set after erasing 30: 10 20 40 50
8. Queue and stack
A "queue" data structure is a linear arrangement that adheres to the First-In-First-Out (FIFO) concept. Elements are added at the back (enqueue) and removed from the front (dequeue) in a queue. This mimics a physical queue or line, ensuring that the first person to arrive is the first to be served.
A "stack" in computer science refers to a linear data structure that adheres to the Last-in-First-Out (LIFO) concept. In this structure, elements are either added to or removed from the top of the stack. Visualize it as a stack of plates, allowing you to only access the top plate.
Example:
#include <iostream>
#include <queue>
int main() {
std::queue<int> myQueue;
myQueue.push(10);
myQueue.push(20);
myQueue.push(30);
while (!myQueue.empty()) {
std::cout << myQueue.front() << " ";
myQueue.pop();
}
return 0;
}
Output:
10 20 30
9. String manipulation
In C++, manipulating strings can be achieved using the <string> header and various string functions provided by the C++ Standard Library. Here are some commonly utilized string manipulation functions in C++:
Example:
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <sstream>
int main() {
// Concatenation
std::string result = "Hello, " + "World!";
std::cout << "Concatenation: " << result << std::endl;
// String Length
std::string myString = "Hello, World!";
std::cout << "Length: " << myString.length() << std::endl;
// Substring Extraction
std::cout << "Substring: " << myString.substr(7, 5) << std::endl;
// String Comparison
std::cout << "Comparison Result: " << "apple".compare("banana") << std::endl;
// String Searching
std::cout << "Search Position: " << myString.find("World") << std::endl;
// String Replacement
myString.replace(7, 5, "Universe");
std::cout << "After Replacement: " << myString << std::endl;
// String to Integer Conversion
std::cout << "Integer Conversion: " << std::stoi("123") << std::endl;
// Character Removal
std::string stringWithSpaces = "Remove spaces from here";
stringWithSpaces.erase(std::remove(stringWithSpaces.begin(), stringWithSpaces.end(), ' '), stringWithSpaces.end());
std::cout << "After Removing Spaces: " << stringWithSpaces << std::endl;
// String Tokenization
std::istringstream iss("apple orange banana");
std::vector<std::string> tokens{std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}};
std::cout << "Tokenization:";
for (const auto& token : tokens) std::cout << " " << token;
std::cout << std::endl;
// String Conversion to Uppercase/Lowercase
std::string str = "Convert Me";
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
std::cout << "Uppercase: " << str << std::endl;
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << "Lowercase: " << str << std::endl;
return 0;
}
Output:
Concatenation: Hello, World!
Length: 13
Substring: World
Comparison Result: -1
Search Position: 7
After Replacement: Hello, Universe!
Integer Conversion: 123
After Removing Spaces: Removespacesfromhere
Tokenization: apple orange banana
Uppercase: CONVERT ME TO UPPERCASE
Lowercase: convert me to lowercase
10. Math functions
In C++, mathematical functions play a crucial role in the standard library and are mainly established by the "cmath" header ("math" in C). These functions encompass a broad spectrum of mathematical operations, ranging from fundamental arithmetic to complex mathematical computations. Below is a concise overview of a selection of frequently used mathematical functions in C++:
Example:
#include <iostream>
#include <cmath>
int main () {
// Arithmetic operations
int a = 10, b = 3;
double result_addition = a + b;
double result_subtraction = a - b;
double result_multiplication = a * b;
double result_division = static_cast<double>(a) / b;
std::cout << "Arithmetic Operations:\n";
std::cout << "Addition: " << result_addition << "\n";
std::cout << "Subtraction: " << result_subtraction << "\n";
std::cout << "Multiplication: " << result_multiplication << "\n";
std::cout << "Division: " << result_division << "\n\n";
// Power and Exponentiation
double base = 2.0, exponent = 3.0;
double result_power = std::pow(base, exponent);
double result_sqrt = std::sqrt(16.0);
std::cout << "Power and Exponentiation:\n";
std::cout << "Power: " << result_power << "\n";
std::cout << "Square Root: " << result_sqrt << "\n\n";
// Trigonometric Functions
double angle_degrees = 45.0;
double angle_radians = angle_degrees * M_PI / 180.0;
double result_sin = std::sin(angle_radians);
double result_cos = std::cos(angle_radians);
double result_tan = std::tan(angle_radians);
std::cout << "Trigonometric Functions:\n";
std::cout << "Sine: " << result_sin << "\n";
std::cout << "Cosine: " << result_cos << "\n";
std::cout << "Tangent: " << result_tan << "\n\n";
// Logarithmic Functions
double value_log = 10.0;
double result_log = std::log(value_log);
double result_log10 = std::log10(value_log);
std::cout << "Logarithmic Functions:\n";
std::cout << "Natural Logarithm: " << result_log << "\n";
std::cout << "Log Base 10: " << result_log10 << "\n\n";
// Rounding Functions
double value_round = 4.6;
double result_ceil = std::ceil(value_round);
double result_floor = std::floor(value_round);
double result_round = std::round(value_round);
std::cout << "Rounding Functions:\n";
std::cout << "Ceil: " << result_ceil << "\n";
std::cout << "Floor: " << result_floor << "\n";
std::cout << "Round: " << result_round << "\n";
return 0;
}
Output:
Arithmetic Operations:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.33333
Power and Exponentiation:
Power: 8
Square Root: 4
Trigonometric Functions:
Sine: 0.707107
Cosine: 0.707107
Tangent: 1
Logarithmic Functions:
Natural Logarithm: 2.30259
Log Base 10: 1
Rounding Functions:
Ceil: 5
Floor: 4
Round: 5
Conclusion:
Competitive coding necessitates a robust collection of C++ functions to navigate intricate problem-solving situations swiftly and effectively. The key components include the input and output stream functions cin and cout, renowned for their rapidity and straightforwardness. In contrast to traditional scan-and-print functions, these utilities provide a quicker I/O process, a crucial element in time-constrained contests where even milliseconds can be significant. Serving as the foundation of any resolution, they adeptly manage user inputs and outputs with unparalleled efficiency.
Container manipulation plays a vital role in concurrent programming, with the vector class standing out from a dynamic set due to its support for constant-time random access operations. The vector's ability to resize dynamically makes it a flexible option that can cater to varying algorithmic requirements. Moreover, the String class offers an array of methods for managing strings, offering a robust solution for tasks involving text processing and manipulation. Algorithms form the core of problem-solving, and C++ offers a range of functions such as sorting, translating, and searching, simplifying these essential operations.
In particular, sorting is a key feature of many problems, and C++'s powerful sorting algorithm ensures optimal performance even under tight time constraints. <cmath> library introduces the mathematical functions needed to solve numerical calculation problems. These tools allow developers to solve various mathematical challenges, from basic arithmetic operations to advanced trigonometric functions (sin, cos, tan) and logarithmic functions ( log, log10 ) . However, it is important to note that trigonometric functions usually assume angles in radians, which requires careful conversion for problems involving degrees. Row and stack operations are crucial to the implementation of the data structures required by many algorithms. C++ provides easy-to-use interfaces with queue and stack classes that simplify the implementation of breadth-first and depth-first search algorithms and solve problems where these constructs prove invaluable. Sets and cards <set> and <map> headers are important for handling unique keys and association containers. The set class ensures that elements are unique, while the map class associates values with unique keys, providing an efficient way to manage data relationships. These containers are often crucial for effectively solving problems where the uniqueness of elements or relationships is key. Iterators like begin and end provide a clean and concise way to iterate through containers, making it easier to iterate over elements. Efficient iteration is critical to many algorithms, and C++ iterators provide a unified interface that improves code readability and maintainability. Bitwise operations (&, |, ^, <<, >>) open the gate to precise manipulation of binary data. In competitive programming, where bit manipulation can significantly optimize solutions, understanding and using these features can lead to more efficient and elegant code.
The ternary operator serves as a compact indicator for structuring conditional statements. Its succinct syntax empowers developers to express conditional operations with sophistication, streamlining code length without compromising clarity. The top 10 commonly employed pre-installed C++ functions for competitive coding constitute a formidable suite that empowers programmers to effectively tackle a diverse range of problems. Whether managing input and output, manipulating data structures, utilizing algorithms, working with collections, executing mathematical computations, or crafting concise evaluations, these functions stand as indispensable assets in the toolkit of a competitive coder. Proficiency in these functions, coupled with a comprehension of their intricacies and efficiency, equips developers to navigate the intricacies of competitive coding with finesse and accuracy.