Here’s a C++ cheat sheet:
Basic Syntax
// Hello World
#include <iostream>
int main() {
std::cout << "Hello, C++!" << std::endl;
return 0;
}
// Variables and Data Types
int myInteger = 42;
double myDouble = 3.14;
char myChar = 'A';
bool myBool = true;
// Input/Output
std::cin >> myInteger;
std::cout << "Value: " << myInteger << std::endl;
// Constants
const double PI = 3.14159;
// Arrays and Vectors
int myArray[3] = {1, 2, 3};
std::vector<int> myVector = {4, 5, 6};
// Control Flow
if (condition) {
// Code to execute
} else if (anotherCondition) {
// Code to execute if the first condition is false and this one is true
} else {
// Code to execute if all conditions are false
}
for (int i = 0; i < 5; ++i) {
// Code to repeat
}
// Functions
int add(int a, int b) {
return a + b;
}
// Structures and Classes
struct MyStruct {
int data;
};
class MyClass {
public:
int getData() const { return data; }
private:
int data;
};
// Pointers and References
int myValue = 42;
int* pointerToValue = &myValue;
int& referenceToValue = myValue;
// Dynamic Memory Allocation
int* dynamicArray = new int[5];
delete[] dynamicArray;
// File I/O
#include <fstream>
std::ofstream outputFile("example.txt");
outputFile << "Hello, File!";
outputFile.close();
// Exception Handling
try {
// Code that may throw an exception
} catch (const std::exception& e) {
// Handle exception
}
Object-Oriented Programming (OOP)
// Inheritance
class BaseClass {
public:
virtual void virtualFunction() {
// Implementation
}
};
class DerivedClass : public BaseClass {
public:
void virtualFunction() override {
// Implementation in the derived class
}
};
// Polymorphism
BaseClass* myObject = new DerivedClass();
myObject->virtualFunction();
// Templates
template<typename T>
T add(T a, T b) {
return a + b;
}
Standard Template Library (STL)
#include <vector>
#include <algorithm>
// Vectors
std::vector<int> myVector = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
// Sorting
std::sort(myVector.begin(), myVector.end());
// Iterators
for (auto it = myVector.begin(); it != myVector.end(); ++it) {
// Accessing elements using iterators
}
// Algorithms
int sum = std::accumulate(myVector.begin(), myVector.end(), 0);
This C++ cheat sheet covers basic syntax, variables, control flow, functions, structures, classes, pointers, OOP concepts, templates, and the STL. Adjust as needed for your specific C++ programming requirements.