1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M9 Algorithms
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
11Hrs
37Mins
16Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. Cpp
  5. Cpp M9 Algorithms

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
11Hrs
37Mins
16Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Algorithms

Overview

The <algorithm> header is the crown jewel of C++. It contains over 100 heavily-optimized, production-ready mathematical and structural algorithms (like sorting, searching, reversing, counting, and shuffling).

Because these algorithms operate entirely on Iterators, they are completely agnostic. You can pass std::sort() the iterators for a Vector of Integers, a raw C-array of Doubles, or a Deque of Custom Objects, and it will instantly compile highly optimized machine code for that specific scenario, saving you thousands of hours of rewriting code.

Syntax

cpp
#include <iostream>
#include <vector>
#include <algorithm> // CRITICAL: Must include this!

int main() {
    std::vector<int> data = {42, 10, 99, 10, 5};
    
    // 1. SORTING (Ascending by default)
    std::sort(data.begin(), data.end()); 
    // Now: 5, 10, 10, 42, 99
    
    // 2. REVERSING (Flips the data instantly)
    std::reverse(data.begin(), data.end()); 
    // Now: 99, 42, 10, 10, 5
    
    // 3. COUNTING
    int tens = std::count(data.begin(), data.end(), 10); // Returns 2!
    
    return 0;
}

Common Pitfalls

  • Using std::find() on a std::map or std::set. While you can technically pass map iterators into the global std::find() algorithm, it executes a slow $O(N)$ linear scan. Maps have their own built-in .find() method that utilizes the Red-Black Tree for a blazing fast $O(log N)$ search. Always use the built-in method for associative containers.

Interview Questions

How do you force std::sort() to sort objects in Descending order, or to sort custom classes (like sorting Players by Score)?

The std::sort function takes an optional 3rd parameter called a 'Comparator'. This can be a custom function or a Lambda Expression that returns a boolean dictating how two elements should be compared (e.g., return a > b; for descending order).

Real-World Example

Using a Custom Comparator (Lambda Expression) to sort a vector of complex Objects by a specific private variable.

example
cpp
#include <iostream>
#include <vector>
#include <algorithm>

struct Player {
    int score;
};

int main() {
    std::vector<Player> lobby = {{50}, {99}, {10}};
    
    // We pass a Lambda function as the 3rd argument!
    // It tells the algorithm: "A goes before B if A's score is LARGER."
    std::sort(lobby.begin(), lobby.end(), [](Player a, Player b) {
        return a.score > b.score; 
    });
    
    // Lobby is now sorted: 99, 50, 10
    std::cout << "Winner: " << lobby[0].score << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Algorithms with these quick questions.

Question 1

Which STL algorithm would you use to efficiently search for a specific value in a MASSIVE vector that has already been sorted using `std::sort`?

Take C++ Quiz
Outline
IntroductionEnvironment SetupSyntax & StructureOutput (cout)Comments
Variables & ConstantsData TypesType ModifiersInput (cin)Basic OperatorsLogical & BitwiseType Casting
If...ElseSwitch StatementTernary OperatorWhile & Do-While LoopsFor LoopBreak & Continue
ArraysMulti-Dimensional ArraysC-Style Stringsstd::stringStructsEnums
FunctionsParametersReturn ValuesPass by ReferenceDefault ArgumentsOverloadingInline FunctionsRecursion
Memory AddressesPointersDereferencingPointers & ArraysPointer ArithmeticDynamic MemoryReferences
OOP IntroClasses & ObjectsAccess ModifiersClass MethodsConstructorsDestructorsEncapsulation, Getters & Setters
InheritanceInheritance ConstructorsPolymorphismOperator OverloadingRuntime Poly (Virtual)Abstract ClassesFriend FunctionsThe 'this' Pointer
STL IntroSequence ContainersAssociative ContainersUnordered ContainersContainer AdaptersIteratorsAlgorithms
ExceptionsTry/CatchCatch Allstd::exceptionFile StreamsReading Files & EOF
Templates (Generics)Smart PointersLambdasPreprocessorNamespaces
C++

Algorithms

Overview

The <algorithm> header is the crown jewel of C++. It contains over 100 heavily-optimized, production-ready mathematical and structural algorithms (like sorting, searching, reversing, counting, and shuffling).

Because these algorithms operate entirely on Iterators, they are completely agnostic. You can pass std::sort() the iterators for a Vector of Integers, a raw C-array of Doubles, or a Deque of Custom Objects, and it will instantly compile highly optimized machine code for that specific scenario, saving you thousands of hours of rewriting code.

Syntax

cpp
#include <iostream>
#include <vector>
#include <algorithm> // CRITICAL: Must include this!

int main() {
    std::vector<int> data = {42, 10, 99, 10, 5};
    
    // 1. SORTING (Ascending by default)
    std::sort(data.begin(), data.end()); 
    // Now: 5, 10, 10, 42, 99
    
    // 2. REVERSING (Flips the data instantly)
    std::reverse(data.begin(), data.end()); 
    // Now: 99, 42, 10, 10, 5
    
    // 3. COUNTING
    int tens = std::count(data.begin(), data.end(), 10); // Returns 2!
    
    return 0;
}

Common Pitfalls

  • Using std::find() on a std::map or std::set. While you can technically pass map iterators into the global std::find() algorithm, it executes a slow $O(N)$ linear scan. Maps have their own built-in .find() method that utilizes the Red-Black Tree for a blazing fast $O(log N)$ search. Always use the built-in method for associative containers.

Interview Questions

How do you force std::sort() to sort objects in Descending order, or to sort custom classes (like sorting Players by Score)?

The std::sort function takes an optional 3rd parameter called a 'Comparator'. This can be a custom function or a Lambda Expression that returns a boolean dictating how two elements should be compared (e.g., return a > b; for descending order).

Real-World Example

Using a Custom Comparator (Lambda Expression) to sort a vector of complex Objects by a specific private variable.

example
cpp
#include <iostream>
#include <vector>
#include <algorithm>

struct Player {
    int score;
};

int main() {
    std::vector<Player> lobby = {{50}, {99}, {10}};
    
    // We pass a Lambda function as the 3rd argument!
    // It tells the algorithm: "A goes before B if A's score is LARGER."
    std::sort(lobby.begin(), lobby.end(), [](Player a, Player b) {
        return a.score > b.score; 
    });
    
    // Lobby is now sorted: 99, 50, 10
    std::cout << "Winner: " << lobby[0].score << "\n";
    return 0;
}

Check Your Knowledge

Test your understanding of Algorithms with these quick questions.

Question 1

Which STL algorithm would you use to efficiently search for a specific value in a MASSIVE vector that has already been sorted using `std::sort`?

Take C++ Quiz

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A

C++ coding notes for Indian students — 72 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in C++

  1. Introduction
  2. Environment Setup
  3. Syntax & Structure
  4. Output (cout)
  5. Comments
  6. Variables & Constants
  7. Data Types
  8. Type Modifiers
  9. Input (cin)
  10. Basic Operators
  11. Logical & Bitwise
  12. Type Casting
  13. If...Else
  14. Switch Statement
  15. Ternary Operator
  16. While & Do-While Loops
  17. For Loop
  18. Break & Continue
  19. Arrays
  20. Multi-Dimensional Arrays
  21. C-Style Strings
  22. std::string
  23. Structs
  24. Enums
  25. Functions
  26. Parameters
  27. Return Values
  28. Pass by Reference
  29. Default Arguments
  30. Overloading
  31. Inline Functions
  32. Recursion
  33. Memory Addresses
  34. Pointers
  35. Dereferencing
  36. Pointers & Arrays
  37. Pointer Arithmetic
  38. Dynamic Memory
  39. References
  40. OOP Intro
  41. Classes & Objects
  42. Access Modifiers
  43. Class Methods
  44. Constructors
  45. Destructors
  46. Encapsulation, Getters & Setters
  47. Inheritance
  48. Inheritance Constructors
  49. Polymorphism
  50. Operator Overloading
  51. Runtime Poly (Virtual)
  52. Abstract Classes
  53. Friend Functions
  54. The 'this' Pointer
  55. STL Intro
  56. Sequence Containers
  57. Associative Containers
  58. Unordered Containers
  59. Container Adapters
  60. Iterators
  61. Algorithms
  62. Exceptions
  63. Try/Catch
  64. Catch All
  65. std::exception
  66. File Streams
  67. Reading Files & EOF
  68. Templates (Generics)
  69. Smart Pointers
  70. Lambdas
  71. Preprocessor
  72. Namespaces

Study next

  • All coding notes
  • C++ notes home
  • C++ certification quiz
  • Online compiler
  • Interview Q&A