Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

C++ Tutorial

C++ HOME C++ Intro C++ Get Started C++ Syntax C++ Output C++ Comments C++ Variables C++ User Input C++ Data Types C++ Operators C++ Strings C++ Math C++ Booleans C++ If...Else C++ Switch C++ While Loop C++ For Loop C++ Break/Continue C++ Arrays C++ Structures C++ Enums C++ References C++ Pointers

C++ Functions

C++ Functions C++ Function Parameters C++ Function Overloading C++ Scope C++ Recursion

C++ Classes

C++ OOP C++ Classes/Objects C++ Class Methods C++ Constructors C++ Access Specifiers C++ Encapsulation C++ Inheritance C++ Polymorphism C++ Files C++ Exceptions C++ Date

C++ Data Structures

C++ Data Structures & STL C++ Vectors C++ List C++ Stacks C++ Queues C++ Deque C++ Sets C++ Maps C++ Iterators C++ Algorithms

C++ How To

C++ Add Two Numbers C++ Random Numbers

C++ Reference

C++ Reference C++ Keywords C++ <iostream> C++ <fstream> C++ <cmath> C++ <string> C++ <cstring> C++ <ctime> C++ <vector> C++ <algorithm>

C++ Examples

C++ Examples C++ Real-Life Examples C++ Compiler C++ Exercises C++ Quiz C++ Syllabus C++ Study Plan C++ Certificate


C++ Algorithm


C++ Algorithms

In the previous chapters, you learned that data structures (like vectors, lists, etc) are used to store and organize data.

Algorithms are used to solve problems by sorting, searching, and manipulating data structures.

The <algorithm> library provides many useful functions to perform these tasks with iterators.

To use these functions, you must include the <algorithm> header file:

// Include the algorithm library
#include <algorithm>

Sorting Algorithms

To sort elements in a data structure, you can use the sort() function.

The sort() function takes iterators (typically a start iterator returned by begin() and an end iterator returned by end()) as parameters:

Example

// Create a vector called cars that will store strings
vector<string> cars = {"Volvo", "BMW", "Ford", "Mazda"};

// Sort cars alphabetically
sort(cars.begin(), cars.end());
Try it Yourself »

By default, the elements are sorted in ascending order. In the example above, the elements are sorted alphabetically since they are strings.

If we had a vector of integers, they would be sorted numerically:

Example

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Sort numbers numerically
sort(numbers.begin(), numbers.end());
Try it Yourself »

To reverse the order, you can use rbegin() and rend() instead of begin() and end():

Example

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Sort numbers numerically in reverse order
sort(numbers.rbegin(), numbers.rend());
Try it Yourself »

To only sort specific elements, you could write:

Example

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Sort numbers numerically, starting from the fourth element (only sort 5, 9, and 2)
sort(numbers.begin() + 3, numbers.end());
Try it Yourself »

Searching Algorithms

To search for specific elements in a vector, you can use the find() function.

It takes three parameters: start_iterator, end_iterator, value, where value is the value to search for:

Example

Seach for the number 3 in "numbers":

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Search for the number 3
auto it = find(numbers.begin(), numbers.end(), 3);
Try it Yourself »

To search for the first element that is greater than a specific value, you can use the upper_bound() function:

Example

Find the first value greater than 5 in "numbers":

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Sort the vector in ascending order
sort(numbers.begin(), numbers.end());

// Find the first value that is greater than 5 in the sorted vector
auto it = upper_bound(numbers.begin(), numbers.end(), 5);
Try it Yourself »

The upper_bound() function is typically used on sorted data structures. That's why we first sort the vector in the example above.

To find the smallest element in a vector, use the min_element() function:

Example

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Find the smallest number
auto it = min_element(numbers.begin(), numbers.end());
Try it Yourself »

To find the largest element, use the max_element() function:

Example

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Find the largest number
auto it = max_element(numbers.begin(), numbers.end());
Try it Yourself »

Modifying Algorithms

To copy elements from one vector to another, you can use the copy() function:

Example

Copy elements from one vector to another:

// Create a vector called numbers that will store integers
vector<int> numbers = {1, 7, 3, 5, 9, 2};

// Create a vector called copiedNumbers that should store 6 integers
vector<int> copiedNumbers(6);

// Copy elements from numbers to copiedNumbers
copy(numbers.begin(), numbers.end(), copiedNumbers.begin());
Try it Yourself »

To fill all elements in a vector with a value, you can use the fill() function:

Example

Fill all elements in the numbers vector with the value 35:

// Create a vector called numbers that will store 6 integers
vector<int> numbers(6);

// Fill all elements in the numbers vector with the value 35
fill(numbers.begin(), numbers.end(), 35);
Try it Yourself »

Complete Algorithm Reference

For a complete reference of algorithm functions, go to our C++ Algorithm Reference.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.