C++ Code Snippets

Small, practical examples you can reuse. Copy and paste into your editor and experiment.

1. Hello World

// Basic C++ Hello World
#include <iostream>

int main() {
	std::cout << "Hello, Quick Red Tech!\n";
	return 0;
}

2. Read from stdin and sum numbers

#include <iostream>
int main(){
	int a,b; std::cin >> a >> b;
	std::cout << (a + b) << "\n";
}

Simple pattern used in competitive programming and quick utilities.

3. File I/O (read lines)

#include <fstream>
#include <string>
#include <iostream>

int main(){
	std::ifstream in("input.txt");
	std::string line;
	while(std::getline(in, line)){
		std::cout << line << "\n";
	}
}

4. Simple class with constructor

#include <iostream>
#include <string>

class User {
public:
	User(std::string n): name(std::move(n)){}
	void greet() const { std::cout << "Hi, " << name << "\n"; }
private:
	std::string name;
};

int main(){
	User u("Chisom"); u.greet();
}

5. Smart pointer (unique_ptr) example

#include <memory>
#include <iostream>

struct Node { int v; };
int main(){
	auto p = std::make_unique<Node>();
	p->v = 42;
	std::cout << p->v << "\n";
}

6. Thread example (std::thread)

#include <thread>
#include <iostream>

void worker(){ std::cout << "worker running\n"; }
int main(){
	std::thread t(worker);
	t.join();
}

Remember to compile with -pthread on some platforms.

7. STL example: vector + algorithm

#include <vector>
#include <algorithm>
#include <iostream>

int main(){
	std::vector<int> v = {3,1,4,1,5};
	std::sort(v.begin(), v.end());
	for(auto n: v) std::cout << n << ' ';
	std::cout << '\n';
}

Share / Socials

@QuickRedTechTips-x

@quickredtech