TheAlgorithms/C-Plus-Plus
Collection of various algorithms in mathematics, machine learning, computer science and physics implemented in C++ for educational purposes.
Healthy across all four use cases
weakest axisPermissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 7mo ago
- ✓34+ active contributors
- ✓Distributed ownership (top contributor 29% of recent commits)
Show all 7 evidence items →Show less
- ✓MIT licensed
- ✓CI configured
- ✓Tests present
- ⚠Slowing — last commit 7mo ago
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/thealgorithms/c-plus-plus)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/thealgorithms/c-plus-plus on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: TheAlgorithms/C-Plus-Plus
Generated by RepoPilot · 2026-05-09 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/TheAlgorithms/C-Plus-Plus shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across all four use cases
- Last commit 7mo ago
- 34+ active contributors
- Distributed ownership (top contributor 29% of recent commits)
- MIT licensed
- CI configured
- Tests present
- ⚠ Slowing — last commit 7mo ago
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live TheAlgorithms/C-Plus-Plus
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/TheAlgorithms/C-Plus-Plus.
What it runs against: a local clone of TheAlgorithms/C-Plus-Plus — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in TheAlgorithms/C-Plus-Plus | Confirms the artifact applies here, not a fork |
| 2 | License is still MIT | Catches relicense before you depend on it |
| 3 | Default branch master exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 239 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of TheAlgorithms/C-Plus-Plus. If you don't
# have one yet, run these first:
#
# git clone https://github.com/TheAlgorithms/C-Plus-Plus.git
# cd C-Plus-Plus
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of TheAlgorithms/C-Plus-Plus and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "TheAlgorithms/C-Plus-Plus(\\.git)?\\b" \\
&& ok "origin remote is TheAlgorithms/C-Plus-Plus" \\
|| miss "origin remote is not TheAlgorithms/C-Plus-Plus (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(MIT)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"MIT\"" package.json 2>/dev/null) \\
&& ok "license is MIT" \\
|| miss "license drift — was MIT at generation time"
# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
&& ok "default branch master exists" \\
|| miss "default branch master no longer exists"
# 4. Critical files exist
test -f "CMakeLists.txt" \\
&& ok "CMakeLists.txt" \\
|| miss "missing critical file: CMakeLists.txt"
test -f "CONTRIBUTING.md" \\
&& ok "CONTRIBUTING.md" \\
|| miss "missing critical file: CONTRIBUTING.md"
test -f "CodingGuidelines.md" \\
&& ok "CodingGuidelines.md" \\
|| miss "missing critical file: CodingGuidelines.md"
test -f ".clang-format" \\
&& ok ".clang-format" \\
|| miss "missing critical file: .clang-format"
test -f "DIRECTORY.md" \\
&& ok "DIRECTORY.md" \\
|| miss "missing critical file: DIRECTORY.md"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 239 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~209d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/TheAlgorithms/C-Plus-Plus"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
TheAlgorithms/C-Plus-Plus is an educational repository providing 1900+ lines of well-documented C++ implementations of classic algorithms across backtracking, bit manipulation, ciphers, machine learning, graph theory, and numerical computing. It solves the problem of finding clean, reference implementations of fundamental algorithms without external dependencies—pure STL-based code suitable for learning and competitive programming. Flat monorepo organized by algorithm category: backtracking/, bit_manipulation/, ciphers/, etc., each with its own CMakeLists.txt. Top-level CMakeLists.txt orchestrates the build. Each subdirectory contains standalone .cpp files (e.g., backtracking/n_queens.cpp, bit_manipulation/hamming_distance.cpp) with minimal interdependencies. .github/workflows automate testing, linting, and documentation generation.
👥Who it's for
Computer science students, competitive programmers, and educators seeking reference implementations and learning resources. Contributors are algorithm enthusiasts and academics who want to document algorithmic patterns in production-quality C++.
🌱Maturity & risk
Actively maintained and mature. The repository shows strong CI/CD infrastructure (CodeQL, Doxygen, Awesome CI workflows in .github/workflows/), uses CMake for cross-platform builds, and enforces code style via .clang-format and .clang-tidy. Multi-language documentation exists (README, CONTRIBUTING.md, CodingGuidelines.md). This is a stable, community-driven educational resource with established governance (CODEOWNERS, pull request templates).
Low risk for a reference/educational repo. Zero external dependencies (uses only STL) eliminates supply chain concerns. Primary risks are: (1) educational implementations may not be optimized for production workloads, (2) contributor velocity depends on community PRs rather than core maintainers, (3) scope creep across many algorithm categories could dilute code quality. However, code review processes and CI gates mitigate quality concerns.
Active areas of work
Active maintenance: Workflows in .github/workflows/ show automated testing (awesome_workflow.yml, codeql.yml), documentation generation (gh-pages.yml), issue triage (stale.yml), and directory indexing (directory_writer.yml). Pull request template and issue templates (bug_report.yml, feature_request.yml) indicate ongoing structured contributions. DIRECTORY.md is auto-generated, suggesting active catalog maintenance.
🚀Get running
git clone https://github.com/TheAlgorithms/C-Plus-Plus.git
cd C-Plus-Plus
mkdir build && cd build
cmake ..
make
Requires CMake (3.10+) and a C++11 compiler. No other dependencies.
Daily commands: No runtime server. Algorithms are standalone: compile with CMake and run individual executables (each .cpp produces a binary). Example:
cd build
./backtracking/n_queens
./bit_manipulation/hamming_distance
Some algorithms may accept stdin; check specific file headers for usage.
🗺️Map of the codebase
CMakeLists.txt— Root build configuration that orchestrates compilation of all 465 algorithm files across multiple subdirectories; essential for understanding project structure and dependencies.CONTRIBUTING.md— Defines contribution guidelines, code standards, and PR review process that every contributor must follow to maintain consistency across the educational codebase.CodingGuidelines.md— Establishes coding style, naming conventions, and quality standards that all algorithm implementations must adhere to..clang-format— Enforces automated code formatting standards across all C++ files to ensure consistent style across 465 files.DIRECTORY.md— Auto-generated index documenting all 465 algorithm files organized by category; critical reference for navigating the codebase.data_structures/node.hpp— Core header defining reusable node structures for linked lists, trees, and other data structure implementations throughout the repo..github/workflows/codeql.yml— Automated security and quality analysis pipeline that validates all contributions meet minimum code quality standards.
🛠️How to make changes
Add a new algorithm to an existing category
- Create new .cpp file in target category directory (e.g., backtracking/, bit_manipulation/) (
backtracking/new_algorithm.cpp) - Implement algorithm following CodingGuidelines.md conventions: include headers, use namespace std, add comments (
CodingGuidelines.md) - Register new file in category's CMakeLists.txt using add_executable() or add_library() (
backtracking/CMakeLists.txt) - Create main() function or test harness demonstrating algorithm usage (
backtracking/new_algorithm.cpp) - Submit PR; auto-generated DIRECTORY.md will update during CI workflow (
.github/workflows/directory_writer.yml)
Add a new data structure
- Create .cpp or .hpp file in data_structures/ following template of existing structures like stack.hpp or queue.hpp (
data_structures/stack.hpp) - For linked structures, inherit from or use node.hpp template (
data_structures/node.hpp) - Implement operations (insert, delete, search) with clear documentation (
data_structures/binary_search_tree.cpp) - Add CMakeLists.txt entry if creating standalone compilation target (
data_structures/CMakeLists.txt) - Create test file (e.g., test_structure.cpp) to validate correctness (
data_structures/test_stack.cpp)
Add a new algorithm category folder
- Create new directory at root level (e.g., graph_algorithms/) (
backtracking/) - Create CMakeLists.txt in new directory using pattern from existing categories (
backtracking/CMakeLists.txt) - Add subdirectory reference to root CMakeLists.txt: add_subdirectory(graph_algorithms) (
CMakeLists.txt) - Implement algorithm files following CodingGuidelines.md (
CodingGuidelines.md) - CI workflows will auto-discover and process new category (
.github/workflows/awesome_workflow.yml)
🔧Why these technologies
- C++ — Compiled language enables efficient algorithm implementation and performance demonstration suitable for educational purposes; language constraints teach algorithmic efficiency.
- CMake — Cross-platform build system allows 465 independent algorithm files to be selectively compiled without monolithic dependencies; modular growth strategy.
- Clang-Format + Clang-Tidy — Automated enforcement of consistent code style and static analysis across all contributors ensures educational code remains readable and follows best practices.
- GitHub Actions CI/CD — Automated CodeQL security scanning, build verification, and Doxygen documentation generation on every PR catches issues early and keeps documentation current.
- Doxygen — Generates browsable HTML documentation from code comments, making 465 algorithms discoverable and well-documented for learners.
⚖️Trade-offs already made
-
Algorithms stored as independent .cpp files rather than shared library
- Why: Maximizes discoverability; each algorithm is self-contained and compilable in isolation, ideal for educational reference and copy-paste learning.
- Consequence: Code duplication across similar implementations (e.g., multiple queue implementations); no shared compiled artifact.
-
No external dependencies beyond C++ standard library
- Why: Educational clarity: reduces complexity, forces implementations from first principles, works in any C++ environment.
- Consequence: Cannot leverage optimized third-party libraries; implementations may be slower than production alternatives.
-
Template-based data structures (stack.hpp, queue.hpp) alongside concrete implementations
- Why: Teaches both generic programming patterns and concrete examples; templates show advanced C++ while concrete versions remain accessible.
- Consequence: Multiple implementations of same concept increases repo size and could confuse learners about best practices.
-
Auto-generated DIRECTORY.md from file structure
- Why: Keeps index synchronized with actual codebase as files are added; reduces manual maintenance burden.
- Consequence: Directory structure must be well-organized for auto-generation to work correctly; no custom categorization logic.
🚫Non-goals (don't propose these)
- Does not provide production-ready, optimized implementations; educational clarity prioritized over raw performance
- Does not include external dependencies or package manager integration (no vcpkg, conan manifests)
- Not a C++ testing framework; individual algorithm files include basic main() demonstrations rather than formal unit test suites
- Not a real-time system; includes CPU scheduling algorithms as examples only, not actual OS schedulers
🪤Traps & gotchas
- CMake minimum version: CMakeLists.txt likely requires CMake 3.10+; older systems may fail silently. 2. C++ standard: Code uses C++11 features (std::unique_ptr, lambdas); older compilers need -std=c++11 flag explicitly. 3. clang-tidy enforcement: Strict linting rules in .clang-tidy may reject valid code patterns (e.g., magic numbers without explanatory constants); check .clang-tidy before assuming code is wrong. 4. No external testing framework: Tests are compile-only; runtime correctness often relies on main() demonstration code or manual verification. 5. Gitpod environment: .gitpod.yml and .gitpod.dockerfile suggest web-based development; local setups must manually install CMake and C++ toolchain.
🏗️Architecture
💡Concepts to learn
- Backtracking with pruning — Core technique in NP-complete problem solving (N-Queens, Sudoku, Knight's Tour in backtracking/); understanding pruning strategies is essential for optimization beyond brute force.
- Bit manipulation optimizations — Low-level performance technique (gray_code.cpp, hamming_distance.cpp) that underpins competitive programming and kernel-level algorithms; teaches binary representations and bitwise operations.
- Graph coloring and constraint satisfaction — Fundamental NP-complete problem (graph_coloring.cpp); demonstrates how backtracking applies to real-world scheduling and register allocation problems.
- Travelling Salesman Problem (TSP) — Canonical NP-hard optimization problem solved via bit manipulation (travelling_salesman_using_bit_manipulation.cpp) using dynamic programming with bitmask; teaches exponential-time approximation algorithms.
- Minimax algorithm with game trees — Foundation of adversarial AI and game theory (minimax.cpp); used in chess engines and zero-sum game solvers; critical for understanding recursive game-state exploration.
- Hamming distance and error-correcting codes — Information theory concept (hamming_distance.cpp) essential for data transmission, checksums, and detecting bit-flip errors in networks and storage systems.
- Gray code (reflected binary code) — Encoding scheme (gray_code.cpp) where consecutive values differ by one bit; used in digital logic, error detection, and hardware state transitions to minimize glitches.
🔗Related repos
TheAlgorithms/Python— Sister repository with identical algorithm collection in Python; reference implementations for polyglot learners and cross-language algorithm comparison.TheAlgorithms/Java— Parallel Java implementations of same algorithms; provides alternative reference for OOP learners and JVM-based competitive programmers.torvalds/linux— Real-world C++ reference for production algorithmic patterns (kernel data structures, bit manipulation, memory management) beyond textbook examples.nlohmann/json— Example of educational C++ library with zero dependencies and strict code quality standards; architectural and CI/CD pattern reference for this repo.competitive-programming-library/competitive-programming-library— Curated competitive programming algorithm templates in C++; overlaps with this repo's focus on reference implementations for algorithmic problem-solving.
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add CMake unit test framework integration for algorithm validation
The repo has CMakeLists.txt files but no visible test infrastructure. With 100+ algorithms across backtracking, bit_manipulation, ciphers, data_structures, and cpu_scheduling_algorithms, adding Google Test (gtest) or Catch2 integration would allow contributors to validate algorithms systematically. This is critical for an educational algorithms repo where correctness is paramount. Currently, algorithms appear to only have main() functions without automated test coverage.
- [ ] Create tests/CMakeLists.txt with Google Test/Catch2 configuration
- [ ] Add sample unit tests for 3-5 existing algorithms (e.g., backtracking/n_queens.cpp, bit_manipulation/power_of_2.cpp)
- [ ] Update root CMakeLists.txt to include tests/ as a subdirectory with enable_testing()
- [ ] Add GitHub Action workflow (.github/workflows/unit_tests.yml) to run tests on PR/push
- [ ] Update CONTRIBUTING.md with test requirements for new algorithm submissions
Create algorithm complexity documentation and add Big-O annotations to source files
The repo lacks standardized documentation of time/space complexity for algorithms. Educational repos benefit enormously from having complexity analysis readily visible. Currently algorithms like sudoku_solver.cpp, travelling_salesman_using_bit_manipulation.cpp, and binary_search_tree.cpp don't have documented Big-O analysis. Adding doxygen-compatible @complexity tags and a COMPLEXITY.md guide would help learners understand algorithm tradeoffs.
- [ ] Create ALGORITHM_COMPLEXITY.md documenting complexity for each major algorithm category
- [ ] Add doxygen @complexity, @time_complexity, @space_complexity tags to 20+ key algorithms
- [ ] Create a complexity-summary table in DIRECTORY.md showing algorithm categories with their Big-O characteristics
- [ ] Add linting check in .clang-tidy or new workflow to flag algorithms missing complexity documentation
- [ ] Document examples for 5 algorithms showing how to analyze and annotate complexity
Add missing CMakeLists.txt files and consolidate scattered algorithms into properly organized subdirectories
The file structure shows CMakeLists.txt only in main directories (backtracking/, bit_manipulation/, etc.) but the repo likely has subdirectories and scattered files. Looking at the incomplete listing, there are algorithms that may not be properly integrated into the build system. Systematic organization with comprehensive CMake integration would make the repo more maintainable and easier for contributors to add new algorithms following established patterns.
- [ ] Audit all algorithm files to identify those not referenced in any CMakeLists.txt
- [ ] Create CMakeLists.txt for any subdirectories missing them (check math/, searching/, sorting/, graph_algorithms/ if they exist)
- [ ] Update root CMakeLists.txt to ensure all subdirectories are included and buildable
- [ ] Add CMAKE_CXX_STANDARD and compiler flags consistently across all CMakeLists.txt files
- [ ] Test full build with: mkdir build && cd build && cmake .. && make to verify all algorithms compile
🌿Good first issues
- Add unit test framework integration: Currently, many algorithms like backtracking/sudoku_solver.cpp have only main() demo code. Introduce Google Test (gtest) or Catch2 integration in CMakeLists.txt and add test_*.cpp files for each major algorithm category. This improves verification without external dependencies.
- Document time/space complexity in algorithm headers: Audit files like bit_manipulation/travelling_salesman_using_bit_manipulation.cpp and add standardized Doxygen comments with @complexity tags (BigO notation). CONTRIBUTING.md mentions this; systematize it across all 1900+ lines.
- Add missing algorithm categories: Scan DIRECTORY.md and identify algorithmic domains mentioned in README but missing directories (e.g., 'dynamic programming', 'greedy algorithms', 'network flow'). Create category folders, seeding with 2-3 canonical implementations and CMakeLists.txt. Coordinate via CONTRIBUTING.md issue discussion.
⭐Top contributors
Click to expand
Top contributors
- @vil02 — 29 commits
- @realstealthninja — 15 commits
- @github-actions[bot] — 12 commits
- @hollowcrust — 4 commits
- @jiya10208 — 3 commits
📝Recent commits
Click to expand
Recent commits
b9c118f— style: remove interaction with the user (#3009) (vil02)ba0d3ff— ci: fix permissions issue with approved-label (#3017) (realstealthninja)b5d818b— ci: use a different action forlabelling on pr approval. (#3016) (realstealthninja)3502150— correct grammar and wording in contribution guidelines (#3012) (Rudra2637)be550cd— ci: bump codeql to v3 (#3008) (realstealthninja)47badd9— chore: fix file formatter (#3007) (realstealthninja)643e0a9— style: remove interaction with the user (#3006) (vil02)8541bb3— Fix: use uint64_t for input and counter in countSetBits (#3003) (Rudra2637)e72b7aa— fix: handle wrong inputs inpostfix_evaluation(#3005) (vil02)07663b0— refactor: input size should not be a template argument inpostfix_evaluation(#2996) (vil02)
🔒Security observations
This is an educational algorithm repository with a generally secure posture. The codebase contains no critical vulnerabilities based on the file structure analysis. Primary concerns are related to the nature of educational code: custom cryptographic implementations, classical cipher implementations that should not be used in production, and the typical lack of comprehensive input validation in educational material. The repository follows good security practices by using GitHub Actions with CodeQL analysis, maintaining proper code review processes (CODEOWNERS, pull request templates), and including security-focused documentation. No exposed secrets, injection vulnerabilities, or critical misconfigurations were identified in the visible structure. The main recommendation is to enhance documentation clearly marking cryptographic and cipher code as educational-only.
- Low · Gitpod Configuration Exposure —
.gitpod.dockerfile, .gitpod.yml. The repository contains .gitpod.dockerfile and .gitpod.yml files which define development environment configurations. While this is a common practice for educational projects, it could potentially expose development setup details. Fix: Ensure sensitive environment variables or credentials are not included in Gitpod configuration files. Use environment variable placeholders instead of hardcoded values. - Low · Custom Integer Type Implementation —
ciphers/uint128_t.hpp, ciphers/uint256_t.hpp. The repository contains custom uint128_t.hpp and uint256_t.hpp implementations in the ciphers directory. Custom cryptographic implementations can be error-prone and may not have undergone proper security audits. Fix: For production cryptographic use, rely on well-established libraries like OpenSSL or libsodium instead of custom implementations. Document that these are for educational purposes only. - Low · Cipher Implementations for Educational Use —
ciphers/ directory (multiple cipher implementations). The codebase contains implementations of classical ciphers (Caesar, Vigenere, XOR, etc.) and modern ciphers. While appropriate for an educational repository, these should not be used for real security applications as they may have implementation vulnerabilities. Fix: Add clear documentation warnings that these cipher implementations are for educational purposes only and should not be used to protect sensitive data in production environments. - Low · Missing Input Validation Documentation —
Various algorithm implementations throughout the repository. The repository appears to contain many algorithm implementations without visible comprehensive input validation patterns. Educational code often lacks defensive programming practices against malformed inputs. Fix: Document expected input constraints and add appropriate input validation and error handling to all public functions, especially in data structure and cryptographic implementations.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.