Concepts for C++
C++ is a powerful, versatile programming language that extends the capabilities of C with features like object-oriented programming, templates, and standard libraries. Developed by Bjarne Stroustrup in the 1980s, C++ is widely used in a variety of domains, including systems programming, game development, and high-performance applications. It offers both low-level control over hardware resources and high-level abstractions for building complex software systems. With its support for features like classes, inheritance, and polymorphism, C++ facilitates the creation of modular, reusable code. Despite its complexity and steep learning curve, C++ remains a popular choice for developers seeking performance, flexibility, and control in their projects.
Print Text
#include <iostream> using namespace std; int main() { cout << "Hello World!"; return 0; }Comments
// one line comment /* multi line comment */
Variables
int carCount = 2; string name = "Joe"; bool isPurple = true;
Data Types
int carCount = 2; unsigned int age = 15; signed short int seaLevel = -10000; long long int usBudget = 11000000000; unsigned long long int lightSpeed = 11799312874; float myGPA = 3.45f; double piValue = 3.14159265; char lastLetter = 'Z'; bool isMale = true; #include <iostream> using namespace std; string myName = "Joe";
Math Op
int carCount = 6; int truckCount = 3; int total = carCount + truckCount; cout << total << endl; int subtract = carCount - truckCount; cout << subtract << endl; int multiple = carCount * truckCount; cout << multiple << endl; int divisible = carCount / truckCount; cout << divisible << endl; // performs division and gets remainder which is 0 int modulo = carCount % truckCount; cout << modulo << endl;
Math Functions
float power = pow(3.0, 6.0); cout << power << endl; float root = sqrt(16.0); cout << root << endl; float floorVal = floor(3.14); cout << floorVal << endl; float ceilVal = ceil(4.3); cout << ceilVal << endl; float roundVal = round(3.4); cout << roundVal << endl; // random number from 0 to 100 random_device rd; mt19937 gen(rd()); uniform_int_distribution<> dis(0, 100); int ranNum = dis(gen); cout << ranNum << endl;
If/Else
int carCount = 6; if (carCount > 3) { cout << "More than three cars"; } else if (carCount == 3) { cout << "Equal to three cars"; } else { cout << "Less than three cars"; }Ternary
int carCount = 3; string result = (carCount > 2) ? "Yes" : "No"; cout << result;
Switch
int carCount = 3; switch (carCount) { case 1: cout << "One car"; break; case 2: cout << "Two cars"; break; case 3: cout << "Three cars"; break; default: cout << "More than three"; }Functions
#include <iostream> int handleCars(int cars, int wheels) { int total = cars * wheels; return total; } int result = handleCars(3, 4); std::cout << result;Interpolation
#include <iostream> // require c++ 20 to use #include <format> using namespace std; string name = "Joe"; string car = "Mazda"; string result = format("{} drives a {}", name, car); cout << result << endl;Type Casting
#include <iostream> #include <math.h> using namespace std; string squareA(int length) { double result = (double)(pow(length, 2)); return to_string(result); } string squareL = "4"; int convertedVal = stoi(squareL); string area = squareA(convertedVal); cout << area << endl;Date and Time
#include <iostream> #include <ctime> using namespace std; // set tieme in seconds since 1970 time_t secondsTime = time(nullptr); tm *localTime = localtime(&secondsTime); // current numeric year int year = 1900 + localTime->tm_year; // current numeric month int month = 1 + localTime->tm_mon; // current numeric day int day = localTime->tm_mday; // formatted date string fullDate = to_string(month) + "/" + to_string(day)+ "/" + to_string(year); cout << secondsTime << endl; cout << year << endl; cout << fullDate << endl;Classes
#include <iostream> #include <string> #include <vector> using namespace std; class Cars { protected: vector<string> carList; public: void addCar(string car) { carList.push_back(car); } void removeFirst() { carList.erase(carList.begin()); } string getFirstVal() { if (carList.size() > 0) { return carList[0]; } return ""; } }; Cars newList; newList.addCar("Honda"); newList.addCar("Mazda"); newList.addCar("Toyota"); newList.removeFirst(); string firstCar = newList.getFirstVal(); cout << firstCar << endl;Inheritance
#include <iostream> using namespace std; class User { protected: string username; string password; public: void setUser(string x, string y) { username = x; password = y; } }; class Admin: public User { protected: string id; public: void setAdmin(string x) { id = x; } string getUsername() { return username; } string getAdminID() { return id; } }; Admin newAdmin; newAdmin.setUser("alpha0", "pw1"); newAdmin.setAdmin("1FE"); cout << newAdmin.getUsername() << "\n"; cout << newAdmin.getAdminID() << "\n";Method Overload
#include <iostream> using namespace std; class UserForm { public: string formA = "alpha"; string formB = "beta"; string formC = "gamma"; string formD = "epsilon"; string getForm(int age) { if (age > 65) { return formA; } return formB ; } string getForm(string formId) { if (formId == "gamma") { return formD; } return formA; } string getForm( bool isMilitary, bool isNasa ) { if (isMilitary || isNasa) { return formD; } return formA; } }; UserForm form; int myAge = 67; string myId = "1FE"; bool veteran = false; bool nasa = true; string form1 = form.getForm(myAge); string form2 = form.getForm(myId); string form3 = form.getForm(veteran, nasa); cout << form1 << endl; cout << form2 << endl; cout << form3 << endl;Abstract Class
#include <iostream> using namespace std; class Animation { public: // optional to implement virtual void walk(){}; // mandatory to implement virtual void run() = 0; virtual void idle() = 0; }; class Human: public Animation { public: void walk() { cout << "Human walks" << endl; } void run() { cout << "Human runs" << endl; } void idle() { cout << "Human idles" << endl; } }; class Zombie: public Animation { public: void run() { cout << "Zombie runs" << endl; } void idle() { cout << "Zombie idles" << endl; } }; Human player; player.walk(); Zombie boss1; boss1.run();Static Class
#include <iostream> #include <math.h> using namespace std; // Not used in classes // used in methods and variables only class Helper { public: static double CircleA(int radius) { double power = pow(radius, 2); return (double)(3.14 * power); } static double SquareA(int length) { return (double)(pow(length, 2)); } }; double circle = Helper::CircleA(3); cout << circle << endl; double square = Helper::SquareA(4); cout << square << endl;Arrays/Lists
#include <iostream> #include <string> #include <vector> using namespace std; vector<string> names = {"Joe", "Alex", "Bob"}; names[1] = "Tom"; string name = names[1]; int numItems = names.size(); cout << name << endl; cout << numItems << endl;Array Methods
#include <iostream> #include <vector> using namespace std; vector<string> cars = {"Honda", "Mazda", "Toyota"}; // 3 elements in vector cout << cars.size() << endl; // Mazda is at index 1 cout << cars.at(1) << endl; // 1st element is Honda cout << cars.front() << endl; // last element is Toyota cout << cars.back() << endl; // replaces entire vector with two Fords cars.assign(2, "Ford"); cout << cars[0] << endl; cout << cars[1] << endl; // add Tesla at the end of vector cars.push_back("Tesla"); cout << cars.back() << endl; // removes last element Tesla cars.pop_back(); cout << cars.back() << endl; // inserts Honda at front of vector cars.insert(0, "Honda"); cout << cars.front() << endl;Concatenation
#include <iostream> #include <vector> using namespace std; vector<string> carListKr = {"Kia", "Hyundai", "Daewoo"}; vector<string> carListJp = {"Honda", "Mazda", "Toyota"}; vector<string> combined; combined.insert( combined.end(), carListKr.begin(), carListKr.end() ); combined.insert( combined.end(), carListJp.begin(), carListJp.end() ); cout << combined[1] << endl; cout << combined[4] << endl;Sort Method
#include <iostream> #include <vector> #include <bits/stdc++.h> using namespace std; vector<int> ages = {5, 3, 1, 6, 7, 4, 19}; sort (ages.begin(), ages.end()); for (int i = 0; i < ages.size(); i++) { cout << ages[i] << endl; }Objects
#include <iostream> #include <vector> using namespace std; class User { public: string First; string Last; int Age; bool Retired; vector<string> CarBrands; void setValues( string first, string last, int age, bool retired, vector<string> carbrands ){ First = first; Last = last; Age = age; Retired = retired; CarBrands = carbrands; } string fullName() { return First + " " + Last; } }; User user; user.setValues( "Joe", "Doe", 23, false, {"Mazda", "Toyota"} ); string fullName = user.fullName(); cout << user.First << endl; cout << user.CarBrands[1] << endl; cout << fullName << endl;Maps (Key/Value)
#include <iostream> #include <map> using namespace std; map<string, string> carMap; carMap["Joe"] = "Toyota"; carMap["Bob"] = "Mazda"; carMap["Tom"] = "Ford"; cout << carMap["Tom"] << endl; carMap.erase("Tom"); cout << carMap.size() << endl;Sets
#include <iostream> #include <set> using namespace std; set<string> cars; cars.insert("Mazda"); cars.insert("Toyota"); cars.insert("Honda"); bool result1 = cars.find("Honda") == cars.end() ? false: true; cout << result1 << endl; cars.erase("Honda"); bool result2 = cars.find("Honda") == cars.end() ? false: true; cout << result2 << endl;Stack
#include <iostream> #include <stack> using namespace std; stack<string> cars; cars.push("Mazda"); cars.push("Toyota"); cars.push("Honda"); cout << cars.top() << endl;; cars.pop(); cout << cars.top() << endl;Queues
#include <iostream> #include <queue> using namespace std; queue<string> cars; cars.push("Mazda"); cars.push("Toyota"); cars.push("Honda"); cout << cars.front() << endl; cars.pop(); cout << cars.front() << endl;Linked List
#include <iostream> using namespace std; struct Node { string value; struct Node *next; }; struct Node* newNode = NULL; class LinkedList { public: struct Node *head = NULL; void addValue(string val) { newNode = (struct Node*) malloc(sizeof(struct Node)); newNode->value = val; if(head == NULL) { head = newNode; } else { struct Node *current = head; while(current->next != NULL) { current = current->next; } current->next = newNode; } } string returnHead() { return head->value; } void traverse() { struct Node *current = head; while(current != NULL) { cout << current->value << endl; current = current->next; } } }; LinkedList carList; carList.addValue("Mazda"); carList.addValue("Toyota"); carList.addValue("Honda"); cout << carList.returnHead() << endl; carList.traverse();Graphs
#include <iostream> #include <queue> #include <stack> #include <map> #include <vector> using namespace std; class Graph { public: map<string, vector<string>> graphMap; void addNode(string val) { graphMap[val] = {}; } void addVertices(string node1, string node2) { if(graphMap.find(node1) == graphMap.end()) { graphMap[node1] = {}; } if(graphMap.find(node2) == graphMap.end()) { graphMap[node2] = {}; } graphMap[node1].push_back(node2); graphMap[node2].push_back(node1); } void breadthTraverse (string start) { queue<string> newQueue; newQueue.push(start); map<string, bool> visited; visited[start] = true; while(newQueue.size() > 0) { string val = newQueue.front(); cout << val << endl; newQueue.pop(); vector<string> tempArr = graphMap[val]; for (int i = 0; i < tempArr.size(); i++) { if (!visited[tempArr[i]]) { newQueue.push(tempArr[i]); visited[tempArr[i]] = true; } } } } void depthTraverse (string start) { stack<string> newStack; newStack.push(start); map<string, bool> visited; visited[start] = true; while(newStack.size() > 0) { string val = newStack.top(); cout << val << endl; newStack.pop(); vector<string> tempArr = graphMap[val]; for (int i = 0; i < tempArr.size(); i++) { if (!visited[tempArr[i]]) { newStack.push(tempArr[i]); visited[tempArr[i]] = true; } } } } }; int main() { Graph newGraph; newGraph.addNode("a"); newGraph.addVertices("a", "b"); newGraph.addVertices("a", "c"); newGraph.addVertices("b", "d"); newGraph.addVertices("b", "e"); newGraph.addVertices("d", "f"); newGraph.addVertices("d", "g"); newGraph.addVertices("d", "h"); newGraph.addVertices("e", "i"); newGraph.addVertices("e", "j"); newGraph.breadthTraverse("a"); newGraph.depthTraverse("a"); return 0; }For Loops
#include <iostream> #include <vector> using namespace std; vector<string> names = {"Joe", "Alex", "Bob"}; for (int i = 0; i < names.size(); i++) { cout << names[i] << endl; }While Loops
#include <iostream> #include <queue> using namespace std; queue<string> carList; carList.push("Mazda"); carList.push("Toyota"); carList.push("Honda"); while(carList.size() > 0) { cout << carList.front() << endl; carList.pop(); } cout << carList.size() << endl;Loop Breaks
#include <iostream> #include <vector> using namespace std; vector<string> cars = {"Toyota", "Honda", "Mazda"}; for (int i = 0; i < cars.size(); i++) { if (cars[i] == "Honda") { cout << "Found at index " << i << endl; break; } cout << "Visited index " << i << endl; }Recursion
#include <iostream> #include <queue> using namespace std; int getSum (queue<int> arr) { if (arr.size() == 0) { return 0; } int firstVal = arr.front(); arr.pop(); return firstVal + getSum(arr); } queue<int> testArr; testArr.push(1); testArr.push(2); testArr.push(3); testArr.push(5); int sum = getSum(testArr); cout << sum << endl;Regex Words
#include <iostream> #include <regex> #include <bits/stdc++.h> using namespace std; string phrase = "I am legend"; regex regexp("[a-za-zA-Z_]*"); smatch result; regex_search(phrase, result, regexp); cout << result.str(0) << endl;Regex Numbers
#include <iostream> #include <regex> #include <bits/stdc++.h> using namespace std; string phrase = "I am 23"; regex regexp("[0-9_]+"); smatch result; regex_search(phrase, result, regexp); cout << result.str(0) << endl;Regex Test
#include <iostream> #include <regex> #include <bits/stdc++.h> using namespace std; string name = "Bob Lee"; regex regexp ("Lee"); smatch m; bool result = regex_search(name, m, regexp); cout << result << endl;Regex Characters
#include <iostream> #include <regex> #include <bits/stdc++.h> using namespace std; string phrase = "##I am legend##"; regex pattern ("#+[a-zA-Z]+"); smatch result; regex_search(phrase, result, pattern); cout << result.str(0) << endl;