Libraries
Libraries in C++ are collections of precompiled functions that you can use in your programs. They provide a set of functions that you can call to perform specific tasks without having to write the code yourself. Libraries are useful for saving time and effort when developing programs, as you can reuse code that has already been written and tested.
Here are some of the common libraries in C++:
<iostream>
The <iostream> library is used for input and output operations in C++. It provides functions like cin and cout for reading input from the user and displaying output to the console. Here is an example of using the <iostream> library:
#include <iostream>
using namespace std;
int main() { string name;
cout << "Enter your name: "; cin >> name;
cout << "Hello, " << name << "!" << endl;
return 0;}In the example above, we include the <iostream> library at the beginning of the program and use the cin and cout functions to read input from the user and display output to the console.
There are also a couple of other functions that are in the same libary, which are cerr and clog. cerr is used for error messages and clog is used for logging messages.
cerr Function
The cerr function is used to display error messages to the console. It is typically used for displaying error messages that need to be shown immediately, such as runtime errors. However, unlike cout, the cerr function does not buffer the output, which means that the error message will be displayed immediately. You can also redirect the output of cerr to a file if needed, instead of displaying it on the console.
Here is an example of using the cerr function:
#include <iostream>#include <fstream>
using namespace std;
int main() { int x = 5; int y = 0;
// Set "error.log" as the output file for the error messages ofstream log("error.log"); cerr.rdbuf(log.rdbuf()); // rdbuf basically means "Read Buffer"
// Write an error message if 0 is divided by 0 if(y == 0) { cerr << "Division by zero: " << x << " / " << y << "\n"; cout << "An error occurred. Check the log file for details."; } else { cout << (x / y); }
log.close();
return 0;}clog Function
The clog function is used to display logging messages to the console. It is typically used for displaying informational messages that are not critical to the program’s execution. The clog function buffers the output, which means that the logging messages will be displayed in an orderly manner. You can also redirect the output of clog to a file if needed, instead of displaying it on the console.
Here is an example of using the clog function:
#include <iostream>#include <fstream>
using namespace std;
int main() { int x = 5; int y = 0;
// Set "log.log" as the output file for the logging messages ofstream log("log.log"); clog.rdbuf(log.rdbuf()); // rdbuf basically means "Read Buffer"
// Write a logging message if 0 is divided by 0 if(y == 0) { clog << "Division by zero: " << x << " / " << y << "\n"; cout << "An error occurred. Check the log file for details."; } else { cout << (x / y); }
log.close();
return 0;}Difference between cout, cerr, and clog
In C++, cout, cerr, and clog are all part of the standard I/O streams used to send output to the console, but they serve slightly different purposes:
cout(Standard Output Stream)
- Used for normal output.
- The data is buffered, meaning it may not appear on the console immediately but is stored temporarily and displayed when the buffer is flushed (automatically or manually).
cerr(Standard Error Stream)
- Used for error messages or critical information.
- The data is unbuffered, meaning it is sent directly to the console without delay.
- Suitable for logging errors or debugging information.
clog(Standard Logging Stream)
- Used for logging information.
- The data is buffered, like
cout, so it may not appear immediately. - It’s generally used for less critical messages, such as status updates or logs.
<fstream>
The <fstream> library is used for file input and output operations in C++. It provides classes like ifstream, ofstream, and fstream for reading from and writing to files. Here is an example of using the <fstream> library:
#include <iostream>#include <fstream>
using namespace std;
int main() { ofstream file("output.txt");
if(file.is_open()) { file << "Hello, world!" << endl; file.close(); } else { cerr << "Error opening file." << endl; }
return 0;}In the example above, we include the <fstream> library at the beginning of the program and use the ofstream class to write to a file named output.txt. We check if the file is open before writing to it and close the file after writing the data.
ifstream Class
The ifstream class is used for reading input from a file. You can use the ifstream class to open a file for reading and read data from the file. Here is an example of using the ifstream class:
#include <iostream>#include <fstream>
using namespace std;
int main() { ifstream file("input.txt"); string line;
if(file.is_open()) { while(getline(file, line)) { cout << line << endl; }
file.close(); } else { cerr << "Error opening file." << endl; }
return 0;}In the example above, we use the ifstream class to open a file named input.txt for reading. We read data from the file line by line using the getline function and display the data to the console.
ofstream Class
The ofstream class is used for writing output to a file. You can use the ofstream class to open a file for writing and write data to the file. Here is an example of using the ofstream class:
#include <iostream>#include <fstream>
using namespace std;
int main() { ofstream file("output.txt");
if(file.is_open()) { file << "Hello, world!" << endl; file.close(); } else { cerr << "Error opening file." << endl; }
return 0;}In the example above, we use the ofstream class to open a file named output.txt for writing. We write the data "Hello, world!" to the file and close the file after writing the data.
fstream Class
The fstream class is used for reading and writing input to and from a file. You can use the fstream class to open a file for reading and writing and perform both input and output operations on the file. Here is an example of using the fstream class:
#include <iostream>#include <fstream>
using namespace std;
int main() { fstream file("data.txt", ios::in | ios::out);
if(file.is_open()) { string line;
while(getline(file, line)) { cout << line << endl; }
file << "Hello, world!" << endl; file.close(); } else { cerr << "Error opening file." << endl; }
return 0;}In the example above, we use the fstream class to open a file named data.txt for reading and writing. We read data from the file line by line using the getline function and display the data to the console. We also write the data "Hello, world!" to the file and close the file after reading and writing the data.
<cmath>
The <cmath> library is used for mathematical operations in C++. It provides functions like sqrt, pow, sin, cos, and tan for performing common mathematical operations. Here is an example of using the <cmath> library:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 16.0;
cout << "Square root of " << x << " is " << sqrt(x) << endl; cout << "2^3 = " << pow(2, 3) << endl; cout << "sin(90 degrees) = " << sin(90 * M_PI / 180) << endl; cout << "cos(0 degrees) = " << cos(0 * M_PI / 180) << endl; cout << "tan(45 degrees) = " << tan(45 * M_PI / 180) << endl;
return 0;}In the example above, we include the <cmath> library at the beginning of the program and use functions like sqrt, pow, sin, cos, and tan to perform common mathematical operations.
abs() Function
The abs() function is used to calculate the absolute value of a number. The absolute value of a number is the distance of the number from zero on the number line. Here is an example of using the abs() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { int x = -5;
cout << "Absolute value of " << x << " is " << abs(x) << endl;
return 0;}In the example above, we include the <cmath> library at the beginning of the program and use the abs() function to calculate the absolute value of the number -5.
sqrt() Function
The sqrt() function is used to calculate the square root of a number. The square root of a number is the number that, when multiplied by itself, gives the original number. Here is an example of using the sqrt() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 16.0;
cout << "Square root of " << x << " is " << sqrt(x) << endl;
return 0;}cbrt() Function
The cbrt() function is used to calculate the cube root of a number. The cube root of a number is the number that, when multiplied by itself twice, gives the original number. Here is an example of using the cbrt() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 27.0;
cout << "Cube root of " << x << " is " << cbrt(x) << endl;
return 0;}ceil() Function
The ceil() function is used to calculate the smallest integer greater than or equal to a number. It rounds the number up to the nearest integer. Here is an example of using the ceil() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 3.14;
cout << "Ceil of " << x << " is " << ceil(x) << endl;
return 0;}floor() Function
The floor() function is used to calculate the largest integer less than or equal to a number. It rounds the number down to the nearest integer. Here is an example of using the floor() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 3.14;
cout << "Floor of " << x << " is " << floor(x) << endl;
return 0;}exp() Function
The exp() function is used to calculate the exponential value of a number. The exponential value of a number is e raised to the power of the number (En). Here is an example of using the exp() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 2.0;
cout << "Exp of " << x << " is " << exp(x) << endl;
return 0;}exp2() Function
The exp2() function is used to calculate 2 raised to the power of a number (2n). Here is an example of using the exp2() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 3.0;
cout << "Exp2 of " << x << " is " << exp2(x) << endl;
return 0;}expm1() Function
The expm1() function is used to calculate e raised to the power of a number minus one (En-1). Here is an example of using the expm1() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 2.0;
cout << "Expm1 of " << x << " is " << expm1(x) << endl;
return 0;}fdim() Function
The fdim() function is used to calculate the positive difference between two numbers. It returns the difference between the two numbers if the first number is greater than the second number, otherwise it returns 0. Here is an example of using the fdim() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 5.0; double y = 3.0;
cout << "Positive difference between " << x << " and " << y << " is " << fdim(x, y) << endl;
return 0;}fma() Function
The fma() function is used to calculate the fused multiply-add operation. It multiplies two numbers and adds a third number to the result (x * y + z). Here is an example of using the fma() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 2.0; double y = 3.0; double z = 4.0;
cout << "Fused multiply-add of " << x << ", " << y << ", and " << z << " is " << fma(x, y, z) << endl;
return 0;}frexp() Function
The frexp() function is used to break down a number into its mantissa and exponent components. It returns the mantissa and exponent of the number. Here is an example of using the frexp() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 123.45; int exp;
double mantissa = frexp(x, &exp);
cout << "Mantissa of " << x << " is " << mantissa << " and exponent is " << exp << endl;
return 0;}hypot() Function
The hypot() function is used to calculate the hypotenuse of a right-angled triangle given the lengths of the other two sides. It returns the length of the hypotenuse. Here is an example of using the hypot() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 3.0; double y = 4.0;
cout << "Hypotenuse of a right-angled triangle with sides " << x << " and " << y << " is " << hypot(x, y) << endl;
return 0;}ilogb() Function
The ilogb() function is used to calculate the exponent of a floating-point number. It returns the exponent of the number. Here is an example of using the ilogb() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 123.45;
cout << "Exponent of " << x << " is " << ilogb(x) << endl;
return 0;}ldexp() Function
The ldexp() function is used to calculate the product of a number and 2 raised to the power of another number (x*2y). It returns the result of the calculation. Here is an example of using the ldexp() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.5; int exp = 3;
cout << x << " * 2^" << exp << " = " << ldexp(x, exp) << endl;
return 0;}lgamma() Function
The lgamma() function is used to calculate the natural logarithm of the absolute value of the gamma function of a number. It returns the result of the calculation. Here is an example of using the lgamma() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 5.0;
cout << "Logarithm of the absolute value of the gamma function of " << x << " is " << lgamma(x) << endl;
return 0;}log() Function
The log() function is used to calculate the natural logarithm of a number. The natural logarithm of a number is the power to which the base e must be raised to obtain the number. Here is an example of using the log() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 2.0;
cout << "Logarithm of " << x << " is " << log(x) << endl;
return 0;}log10() Function
The log10() function is used to calculate the base 10 logarithm of a number. The base 10 logarithm of a number is the power to which the base 10 must be raised to obtain the number. Here is an example of using the log10() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 100.0;
cout << "Base 10 logarithm of " << x << " is " << log10(x) << endl;
return 0;}log1p() Function
The log1p() function is used to calculate the natural logarithm of a number plus one. It returns the result of the calculation. Here is an example of using the log1p() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Logarithm of " << x << " plus one is " << log1p(x) << endl;
return 0;}log2() Function
The log2() function is used to calculate the base 2 logarithm of a number. The base 2 logarithm of a number is the power to which the base 2 must be raised to obtain the number. Here is an example of using the log2() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 8.0;
cout << "Base 2 logarithm of " << x << " is " << log2(x) << endl;
return 0;}logb() Function
The logb() function is used to calculate the exponent of a floating-point number. It returns the exponent of the number. Here is an example of using the logb() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 123.45;
cout << "Exponent of " << x << " is " << logb(x) << endl;
return 0;}pow() Function
The pow() function is used to calculate the power of a number. It raises the first number to the power of the second number. Here is an example of using the pow() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 2.0; double y = 3.0;
cout << x << " raised to the power of " << y << " is " << pow(x, y) << endl;
return 0;}remainder() Function
The remainder() function is used to calculate the remainder of the division of two numbers. It returns the remainder of the division. Here is an example of using the remainder() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 10.0; double y = 3.0;
cout << "Remainder of " << x << " divided by " << y << " is " << remainder(x, y) << endl;
return 0;}sin() Function
The sin() function is used to calculate the sine of an angle. The sine of an angle is the ratio of the length of the side opposite the angle to the length of the hypotenuse. Here is an example of using the sin() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double angle = 90.0;
cout << "Sine of " << angle << " degrees is " << sin(angle * M_PI / 180) << endl;
return 0;}sinh() Function
The sinh() function is used to calculate the hyperbolic sine of a number. The hyperbolic sine of a number is the ratio of the hyperbolic sine function to the number. Here is an example of using the sinh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Hyperbolic sine of " << x << " is " << sinh(x) << endl;
return 0;}asin() Function
The asin() function is used to calculate the arcsine of a number. The arcsine of a number is the angle whose sine is the number. Here is an example of using the asin() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 0.5;
cout << "Arcsine of " << x << " is " << asin(x) * 180 / M_PI << " degrees" << endl;
return 0;}asinh() Function
The asinh() function is used to calculate the hyperbolic arcsine of a number. The hyperbolic arcsine of a number is the angle whose hyperbolic sine is the number. Here is an example of using the asinh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Hyperbolic arcsine of " << x << " is " << asinh(x) << endl;
return 0;}cos() Function
The cos() function is used to calculate the cosine of an angle. The cosine of an angle is the ratio of the length of the side adjacent to the angle to the length of the hypotenuse. Here is an example of using the cos() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double angle = 0.0;
cout << "Cosine of " << angle << " degrees is " << cos(angle * M_PI / 180) << endl;
return 0;}cosh() Function
The cosh() function is used to calculate the hyperbolic cosine of a number. The hyperbolic cosine of a number is the ratio of the hyperbolic cosine function to the number. Here is an example of using the cosh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Hyperbolic cosine of " << x << " is " << cosh(x) << endl;
return 0;}acos() Function
The acos() function is used to calculate the arccosine of a number. The arccosine of a number is the angle whose cosine is the number. Here is an example of using the acos() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 0.5;
cout << "Arccosine of " << x << " is " << acos(x) * 180 / M_PI << " degrees" << endl;
return 0;}acosh() Function
The acosh() function is used to calculate the hyperbolic arccosine of a number. The hyperbolic arccosine of a number is the angle whose hyperbolic cosine is the number. Here is an example of using the acosh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Hyperbolic arccosine of " << x << " is " << acosh(x) << endl;
return 0;}tan() Function
The tan() function is used to calculate the tangent of an angle. The tangent of an angle is the ratio of the length of the side opposite the angle to the length of the side adjacent to the angle. Here is an example of using the tan() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double angle = 45.0;
cout << "Tangent of " << angle << " degrees is " << tan(angle * M_PI / 180) << endl;
return 0;}tanh() Function
The tanh() function is used to calculate the hyperbolic tangent of a number. The hyperbolic tangent of a number is the ratio of the hyperbolic tangent function to the number. Here is an example of using the tanh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Hyperbolic tangent of " << x << " is " << tanh(x) << endl;
return 0;}atan() Function
The atan() function is used to calculate the arctangent of a number. The arctangent of a number is the angle whose tangent is the number. Here is an example of using the atan() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 1.0;
cout << "Arctangent of " << x << " is " << atan(x) * 180 / M_PI << " degrees" << endl;
return 0;}atanh() Function
The atanh() function is used to calculate the hyperbolic arctangent of a number. The hyperbolic arctangent of a number is the angle whose hyperbolic tangent is the number. Here is an example of using the atanh() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double x = 0.5;
cout << "Hyperbolic arctangent of " << x << " is " << atanh(x) << endl;
return 0;}atan2() Function
The atan2() function is used to calculate the arctangent of the quotient of two numbers. It returns the angle whose tangent is the quotient of the two numbers. Here is an example of using the atan2() function:
#include <iostream>#include <cmath>
using namespace std;
int main() { double y = 1.0; double x = 1.0;
cout << "Arctangent of " << y << " / " << x << " is " << atan2(y, x) * 180 / M_PI << " degrees" << endl;
return 0;}min() and max() Functions
The min() and max() functions are used to calculate the minimum and maximum of two numbers, respectively. They return the minimum and maximum of the two numbers. Here is an example of using the min() and max() functions:
#include <iostream>#include <cmath>
using namespace std;
int main() { int x = 5; int y = 10;
cout << "Minimum of " << x << " and " << y << " is " << min(x, y) << endl; cout << "Maximum of " << x << " and " << y << " is " << max(x, y) << endl;
return 0;}Math Constants
The <cmath> library also provides some mathematical constants like M_PI, M_E, M_LOG2E, M_LOG10E, M_LN2, and M_LN10. These constants represent the values of π, e, log2e, log10e, ln(2), and ln(10), respectively. Here is an example of using the mathematical constants:
#include <iostream>#include <cmath>
using namespace std;
int main() { cout << "Value of pi: " << M_PI << endl; cout << "Value of e: " << M_E << endl; cout << "Value of log2e: " << M_LOG2E << endl; cout << "Value of log10e: " << M_LOG10E << endl; cout << "Value of ln2: " << M_LN2 << endl; cout << "Value of ln10: " << M_LN10 << endl;
return 0;}In the example above, we use the mathematical constants M_PI, M_E, M_LOG2E, M_LOG10E, M_LN2, and M_LN10 to display the values of π, e, log2e, log10e, ln(2), and ln(10), respectively.
Here’s a list of the mathematical constants provided by the <cmath> library:
M_E: The base of the natural logarithm (e).M_LOG2E: The base 2 logarithm of e.M_LOG10E: The base 10 logarithm of e.M_LN2: The natural logarithm of 2.M_LN10: The natural logarithm of 10.M_PI: The value of π.M_PI_2: π/2.M_PI_4: π/4.M_1_PI: 1/π.M_2_PI: 2/π.M_2_SQRTPI: 2/√π.M_SQRT2: √2.M_SQRT1_2: 1/√2.
<ctime>
The <ctime> library is used for date and time operations in C++. It provides functions like time, localtime, strftime, and difftime for working with dates and times. Here is an example of using the <ctime> library:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); string dt = ctime(&now);
cout << "The local date and time is: " << dt;
return 0;}asctime() Function
The asctime() function is used to convert a tm structure to a string representing the date and time. It returns a pointer to a string containing the date and time. Here is an example of using the asctime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); tm *ltm = localtime(&now);
cout << "The local date and time is: " << asctime(ltm);
return 0;}clock() Function
The clock() function is used to get the processor time used by the program. It returns the processor time used by the program in clock ticks. Here is an example of using the clock() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { clock_t start = clock();
for(int i = 0; i < 1000000; i++) { // Do something }
clock_t end = clock(); double duration = double(end - start) / CLOCKS_PER_SEC;
cout << "Time taken: " << duration << " seconds" << endl;
return 0;}difftime() Function
The difftime() function is used to calculate the difference between two times. It returns the difference between the two times in seconds. Here is an example of using the difftime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t start = time(0);
for(int i = 0; i < 1000000; i++) { // Do something }
time_t end = time(0); double duration = difftime(end, start);
cout << "Time taken: " << duration << " seconds" << endl;
return 0;}gmtime() Function
The gmtime() function is used to convert a time_t value to a tm structure representing the UTC time. It returns a pointer to the tm structure. Here is an example of using the gmtime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); tm *gmtm = gmtime(&now);
cout << "The UTC date and time is: " << asctime(gmtm);
return 0;}localtime() Function
The localtime() function is used to convert a time_t value to a tm structure representing the local time. It returns a pointer to the tm structure. Here is an example of using the localtime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); tm *ltm = localtime(&now);
cout << "The local date and time is: " << asctime(ltm);
return 0;}mktime() Function
The mktime() function is used to convert a tm structure to a time_t value representing the local time. It returns the time_t value representing the local time. Here is an example of using the mktime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); tm *ltm = localtime(&now);
time_t local_time = mktime(ltm);
cout << "The local time in seconds is: " << local_time << endl;
return 0;}strftime() Function
The strftime() function is used to format a tm structure into a string. It returns the number of characters written to the string. Here is an example of using the strftime() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0); tm *ltm = localtime(&now); char buffer[80]; // Buffer to store the formatted date and time
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", ltm);
cout << "The local date and time is: " << buffer << endl;
return 0;}time() Function
The time() function is used to get the current calendar time as a time_t value. It returns the current calendar time as a time_t value. Here is an example of using the time() function:
#include <iostream>#include <ctime>
using namespace std;
int main() { time_t now = time(0);
cout << "The current calendar time is: " << now << endl;
return 0;}<vector>
The <vector> library is used for dynamic arrays in C++. It provides the vector class for creating and manipulating dynamic arrays. Here is an example of using the <vector> library:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}vector Class
The vector class is used to create and manipulate dynamic arrays in C++. You can use the vector class to create a dynamic array and perform operations like adding elements, accessing elements, and iterating over the elements. Here is an example of using the vector class:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}In the example above, we create a vector of integers named numbers and initialize it with the values 1, 2, 3, 4, 5. We then iterate over the elements of the vector using a for loop and display the elements to the console.
assign() Function
The assign() function is used to assign new values to a vector. It replaces the existing values in the vector with the new values. Here is an example of using the assign() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.assign({6, 7, 8, 9, 10});
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}at() Function
The at() function is used to access an element at a specific index in a vector. It returns a reference to the element at the specified index. Here is an example of using the at() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Element at index 2: " << numbers.at(2) << endl;
return 0;}back() Function
The back() function is used to access the last element in a vector. It returns a reference to the last element in the vector. Here is an example of using the back() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Last element: " << numbers.back() << endl;
return 0;}begin() and end() Functions
The begin() and end() functions are used to get iterators to the beginning and end of a vector, respectively. They return iterators to the beginning and end of the vector. Here is an example of using the begin() and end() functions:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
for(auto it = numbers.begin(); it != numbers.end(); it++) { cout << *it << " "; }
return 0;}clear() Function
The clear() function is used to remove all elements from a vector. It removes all elements from the vector, leaving it with a size of 0. Here is an example of using the clear() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.clear();
cout << "Size of vector after clearing: " << numbers.size() << endl;
return 0;}empty() Function
The empty() function is used to check if a vector is empty. It returns true if the vector is empty, false otherwise. Here is an example of using the empty() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Is the vector empty? " << (numbers.empty() ? "Yes" : "No") << endl;
return 0;}erase() Function
The erase() function is used to remove elements from a vector at a specific position or range. It removes the element at the specified position or the elements in the specified range. Here is an example of using the erase() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.erase(numbers.begin() + 2);
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}front() Function
The front() function is used to access the first element in a vector. It returns a reference to the first element in the vector. Here is an example of using the front() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
cout << "First element: " << numbers.front() << endl;
return 0;}insert() Function
The insert() function is used to insert elements into a vector at a specific position. It inserts the elements at the specified position in the vector. Here is an example of using the insert() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.insert(numbers.begin() + 2, 10);
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}pop_back() Function
The pop_back() function is used to remove the last element from a vector. It removes the last element from the vector. Here is an example of using the pop_back() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.pop_back();
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}push_back() Function
The push_back() function is used to add elements to the end of a vector. It adds the elements to the end of the vector. Here is an example of using the push_back() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6);
for(int i = 0; i < numbers.size(); i++) { cout << numbers[i] << " "; }
return 0;}rbegin() and rend() Functions
The rbegin() and rend() functions are used to get reverse iterators(which iterate from the end to the beginning) to the beginning and end of a vector, respectively. They return reverse iterators to the beginning and end of the vector. Here is an example of using the rbegin() and rend() functions:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
for(auto it = numbers.rbegin(); it != numbers.rend(); it++) { cout << *it << " "; }
return 0;}size() Function
The size() function is used to get the number of elements in a vector. It returns the number of elements in the vector. Here is an example of using the size() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers = {1, 2, 3, 4, 5};
cout << "Size of vector: " << numbers.size() << endl;
return 0;}swap() Function
The swap() function is used to swap the contents of two vectors. It swaps the contents of the two vectors. Here is an example of using the swap() function:
#include <iostream>#include <vector>
using namespace std;
int main() { vector<int> numbers1 = {1, 2, 3, 4, 5}; vector<int> numbers2 = {6, 7, 8, 9, 10};
numbers1.swap(numbers2);
for(int i = 0; i < numbers1.size(); i++) { cout << numbers1[i] << " "; }
return 0;}<algorithm>
The <algorithm> library is used for performing operations on sequences of elements in C++. It provides functions like sort, find, count, and reverse for working with sequences of elements. Here is an example of using the <algorithm> library:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {5, 2, 8, 1, 3, 7, 4, 6};
sort(numbers, numbers + 8);
for(int i = 0; i < 8; i++) { cout << numbers[i] << " "; }
return 0;}You can use some of the functions provided by the library in sort algorithms, search algorithms and others, lessening the need to write your own functions.
adjacent_find() Function
The adjacent_find() function is used to find the first pair of adjacent elements in a sequence that are equal. It returns an iterator to the first element of the pair. Here is an example of using the adjacent_find() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 3, 4, 5};
auto it = adjacent_find(numbers, numbers + 6);
if(it != numbers + 6) { cout << "First pair of adjacent elements that are equal: " << *it << " " << *(it + 1) << endl; } else { cout << "No pair of adjacent elements that are equal" << endl; }
return 0;}all_of() Function
The all_of() function is used to check if all elements in a sequence satisfy a condition. It returns true if all elements satisfy the condition, false otherwise. Here is an example of using the all_of() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
if(all_of(numbers, numbers + 5, [](int i) { return i > 0; })) { cout << "All elements are greater than 0" << endl; } else { cout << "Not all elements are greater than 0" << endl; }
return 0;}any_of() Function
The any_of() function is used to check if any element in a sequence satisfies a condition. It returns true if any element satisfies the condition, false otherwise. Here is an example of using the any_of() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
if(any_of(numbers, numbers + 5, [](int i) { return i < 0; })) { cout << "At least one element is less than 0" << endl; } else { cout << "No element is less than 0" << endl; }
return 0;}binary_search() Function
The binary_search() function is used to check if an element exists in a sorted sequence. It returns true if the element exists, false otherwise. Here is an example of using the binary_search() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
if(binary_search(numbers, numbers + 5, 3)) { cout << "Element 3 exists in the sequence" << endl; } else { cout << "Element 3 does not exist in the sequence" << endl; }
return 0;}copy() Function
The copy() function is used to copy elements from one sequence to another. It copies the elements from the source sequence to the destination sequence. Here is an example of using the copy() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5}; int copy[5];
copy(numbers, numbers + 5, copy);
for(int i = 0; i < 5; i++) { cout << copy[i] << " "; }
return 0;}count() Function
The count() function is used to count the number of occurrences of an element in a sequence. It returns the number of occurrences of the element. Here is an example of using the count() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5, 3};
int count = count(numbers, numbers + 6, 3);
cout << "Number of occurrences of 3: " << count << endl;
return 0;}count_if() Function
The count_if() function is used to count the number of elements in a sequence that satisfy a condition. It returns the number of elements that satisfy the condition. Here is an example of using the count_if() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
int count = count_if(numbers, numbers + 5, [](int i) { return i % 2 == 0; });
cout << "Number of even elements: " << count << endl;
return 0;}fill() Function
The fill() function is used to fill a sequence with a specific value. It fills the sequence with the specified value. Here is an example of using the fill() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[5];
fill(numbers, numbers + 5, 0);
for(int i = 0; i < 5; i++) { cout << numbers[i] << " "; }
return 0;}find() Function
The find() function is used to find the first occurrence of an element in a sequence. It returns an iterator to the first occurrence of the element. Here is an example of using the find() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto it = find(numbers, numbers + 5, 3);
if(it != numbers + 5) { cout << "Element 3 found at position: " << it - numbers << endl; } else { cout << "Element 3 not found" << endl; }
return 0;}find_first_of() Function
The find_first_of() function is used to find the first occurrence of any element from a set of elements in a sequence. It returns an iterator to the first occurrence of any element from the set. Here is an example of using the find_first_of() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5}; int set[] = {3, 5, 7};
auto it = find_first_of(numbers, numbers + 5, set, set + 3);
if(it != numbers + 5) { cout << "First element from the set found at position: " << it - numbers << endl; } else { cout << "No element from the set found" << endl; }
return 0;}find_if() Function
The find_if() function is used to find the first element in a sequence that satisfies a condition. It returns an iterator to the first element that satisfies the condition. Here is an example of using the find_if() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto it = find_if(numbers, numbers + 5, [](int i) { return i % 2 == 0; });
if(it != numbers + 5) { cout << "First even element found at position: " << it - numbers << endl; } else { cout << "No even element found" << endl; }
return 0;}find_if_not() Function
The find_if_not() function is used to find the first element in a sequence that does not satisfy a condition. It returns an iterator to the first element that does not satisfy the condition. Here is an example of using the find_if_not() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto it = find_if_not(numbers, numbers + 5, [](int i) { return i % 2 == 0; });
if(it != numbers + 5) { cout << "First odd element found at position: " << it - numbers << endl; } else { cout << "No odd element found" << endl; }
return 0;}for_each() Function
The for_each() function is used to apply a function to each element in a sequence. It applies the function to each element in the sequence. Here is an example of using the for_each() function:
#include <iostream>#include <algorithm>
using namespace std;
void print(int i) { cout << i << " ";}
int main() { int numbers[] = {1, 2, 3, 4, 5};
for_each(numbers, numbers + 5, print);
return 0;}includes() Function
The includes() function is used to check if one sequence is a subset of another sequence. It returns true if the first sequence is a subset of the second sequence, false otherwise. Here is an example of using the includes() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers1[] = {1, 2, 3, 4, 5}; int numbers2[] = {2, 4};
if(includes(numbers1, numbers1 + 5, numbers2, numbers2 + 2)) { cout << "numbers2 is a subset of numbers1" << endl; } else { cout << "numbers2 is not a subset of numbers1" << endl; }
return 0;}is_permutation() Function
The is_permutation() function is used to check if one sequence is a permutation of another sequence. It returns true if the first sequence is a permutation of the second sequence, false otherwise. Here is an example of using the is_permutation() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers1[] = {1, 2, 3, 4, 5}; int numbers2[] = {5, 4, 3, 2, 1};
if(is_permutation(numbers1, numbers1 + 5, numbers2)) { cout << "numbers2 is a permutation of numbers1" << endl; } else { cout << "numbers2 is not a permutation of numbers1" << endl; }
return 0;}is_sorted() Function
The is_sorted() function is used to check if a sequence is sorted in ascending order. It returns true if the sequence is sorted, false otherwise. Here is an example of using the is_sorted() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
if(is_sorted(numbers, numbers + 5)) { cout << "numbers is sorted in ascending order" << endl; } else { cout << "numbers is not sorted in ascending order" << endl; }
return 0;}is_sorted_until() Function
The is_sorted_until() function is used to find the first element in a sequence that is out of order. It returns an iterator to the first element that is out of order. Here is an example of using the is_sorted_until() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 5, 4};
auto it = is_sorted_until(numbers, numbers + 5);
if(it != numbers + 5) { cout << "numbers is not sorted at position: " << it - numbers << endl; } else { cout << "numbers is sorted" << endl; }
return 0;}lower_bound() Function
The lower_bound() function is used to find the first element in a sorted sequence that is not less than a specified value. It returns an iterator to the first element that is not less than the specified value. Here is an example of using the lower_bound() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto it = lower_bound(numbers, numbers + 5, 3);
cout << "First element not less than 3 found at position: " << it - numbers << endl;
return 0;}upper_bound() Function
The upper_bound() function is used to find the first element in a sorted sequence that is greater than a specified value. It returns an iterator to the first element that is greater than the specified value. Here is an example of using the upper_bound() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto it = upper_bound(numbers, numbers + 5, 3);
cout << "First element greater than 3 found at position: " << it - numbers << endl;
return 0;}max_element() and min_element() Functions
The max_element() and min_element() functions are used to find the maximum and minimum elements in a sequence, respectively. They return iterators to the maximum and minimum elements in the sequence. Here is an example of using the max_element() and min_element() functions:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
auto max_it = max_element(numbers, numbers + 5); auto min_it = min_element(numbers, numbers + 5);
cout << "Maximum element: " << *max_it << endl; cout << "Minimum element: " << *min_it << endl;
return 0;}merge() Function
The merge() function is used to merge two sorted sequences into a single sorted sequence. It merges the two sorted sequences into a single sorted sequence. Here is an example of using the merge() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers1[] = {1, 3, 5}; int numbers2[] = {2, 4, 6}; int result[6];
merge(numbers1, numbers1 + 3, numbers2, numbers2 + 3, result);
for(int i = 0; i < 6; i++) { cout << result[i] << " "; }
return 0;}none_of() Function
The none_of() function is used to check if none of the elements in a sequence satisfy a condition. It returns true if none of the elements satisfy the condition, false otherwise. Here is an example of using the none_of() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
if(none_of(numbers, numbers + 5, [](int i) { return i < 0; })) { cout << "None of the elements are less than 0" << endl; } else { cout << "At least one element is less than 0" << endl; }
return 0;}random_shuffle() Function
The random_shuffle() function is used to randomly shuffle the elements in a sequence. It shuffles the elements in the sequence randomly. Here is an example of using the random_shuffle() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
random_shuffle(numbers, numbers + 5);
for(int i = 0; i < 5; i++) { cout << numbers[i] << " "; }
return 0;}replace() Function
The replace() function is used to replace all occurrences of a value in a sequence with another value. It replaces all occurrences of the value with the new value. Here is an example of using the replace() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5, 3};
replace(numbers, numbers + 6, 3, 6);
for(int i = 0; i < 6; i++) { cout << numbers[i] << " "; }
return 0;}replace_copy() Function
The replace_copy() function is used to copy a sequence to another sequence and replace all occurrences of a value with another value. It copies the sequence to the destination sequence and replaces all occurrences of the value with the new value. Here is an example of using the replace_copy() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5, 3}; int result[6];
replace_copy(numbers, numbers + 6, result, 3, 6);
for(int i = 0; i < 6; i++) { cout << result[i] << " "; }
return 0;}replace_copy_if() Function
The replace_copy_if() function is used to copy a sequence to another sequence and replace all elements that satisfy a condition with a new value. It copies the sequence to the destination sequence and replaces all elements that satisfy the condition with the new value. Here is an example of using the replace_copy_if() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5}; int result[5];
replace_copy_if(numbers, numbers + 5, result, [](int i) { return i % 2 == 0; }, 0);
for(int i = 0; i < 5; i++) { cout << result[i] << " "; }
return 0;}replace_if() Function
The replace_if() function is used to replace all elements in a sequence that satisfy a condition with a new value. It replaces all elements that satisfy the condition with the new value. Here is an example of using the replace_if() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
replace_if(numbers, numbers + 5, [](int i) { return i % 2 == 0; }, 0);
for(int i = 0; i < 5; i++) { cout << numbers[i] << " "; }
return 0;}reverse() Function
The reverse() function is used to reverse the elements in a sequence. It reverses the elements in the sequence. Here is an example of using the reverse() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5};
reverse(numbers, numbers + 5);
for(int i = 0; i < 5; i++) { cout << numbers[i] << " "; }
return 0;}reverse_copy() Function
The reverse_copy() function is used to copy a sequence to another sequence in reverse order. It copies the sequence to the destination sequence in reverse order. Here is an example of using the reverse_copy() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5}; int result[5];
reverse_copy(numbers, numbers + 5, result);
for(int i = 0; i < 5; i++) { cout << result[i] << " "; }
return 0;}search() Function
The search() function is used to find the first occurrence of a subsequence in a sequence. It returns an iterator to the first occurrence of the subsequence. Here is an example of using the search() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {1, 2, 3, 4, 5, 3, 4, 5}; int subsequence[] = {3, 4, 5};
auto it = search(numbers, numbers + 8, subsequence, subsequence + 3);
if(it != numbers + 8) { cout << "Subsequence found at position: " << it - numbers << endl; } else { cout << "Subsequence not found" << endl; }
return 0;}sort() Function
The sort() function is used to sort the elements in a sequence in ascending order. It sorts the elements in the sequence in ascending order. Here is an example of using the sort() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers[] = {5, 2, 8, 1, 3, 7, 4, 6};
sort(numbers, numbers + 8);
for(int i = 0; i < 8; i++) { cout << numbers[i] << " "; }
return 0;}swap() Function
The swap() function is used to swap the elements of two sequences. It swaps the elements of the two sequences. Here is an example of using the swap() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers1[] = {1, 2, 3, 4, 5}; int numbers2[] = {6, 7, 8, 9, 10};
for(int i = 0; i < 5; i++) { swap(numbers1[i], numbers2[i]); }
for(int i = 0; i < 5; i++) { cout << numbers1[i] << " "; }
return 0;}swap_ranges() Function
The swap_ranges() function is used to swap the elements of two sequences. It swaps the elements of the two sequences. Here is an example of using the swap_ranges() function:
#include <iostream>#include <algorithm>
using namespace std;
int main() { int numbers1[] = {1, 2, 3, 4, 5}; int numbers2[] = {6, 7, 8, 9, 10};
swap_ranges(numbers1, numbers1 + 5, numbers2);
for(int i = 0; i < 5; i++) { cout << numbers1[i] << " "; }
return 0;}