0% found this document useful (0 votes)
5 views2 pages

CPP Reference Card Edit

The document is a C++ reference card that covers various aspects of the language including data types, looping structures, pointers, operators, input/output methods, decision statements, classes, and user-defined data types. It provides examples for each concept to illustrate usage, along with common functions for vectors and strings. The reference card is designed for students in Mississippi State University's CSE1284 and CSE1384 courses.

Uploaded by

nikhilvallabh172
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

CPP Reference Card Edit

The document is a C++ reference card that covers various aspects of the language including data types, looping structures, pointers, operators, input/output methods, decision statements, classes, and user-defined data types. It provides examples for each concept to illustrate usage, along with common functions for vectors and strings. The reference card is designed for students in Mississippi State University's CSE1284 and CSE1384 courses.

Uploaded by

nikhilvallabh172
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

C++ Reference Card Looping Pointers

while Loop Example A pointer variable (or just pointer) is a variable that stores a
C++ Data Types while (expression){ while (x < 100){ memory address. Pointers allow the indirect manipulation of
statement; cout << x++ << endl; data stored in memory.
Data Type Description } }
bool boolean (true or false) while (expression) while (x < 100)
Pointers are declared using *. To set a pointer's value to the
char character ('a', 'b', etc.) { {
address of another variable, use the & operator.
char[] character array (C-style string if null statement; cout << x << endl;
statement; x++;
terminated) Example
} }
string C++ string (from the STL) char c = 'a';
int integer (1, 2, -1, 1000, etc.) char* cPtr;
do-while Loop Example
long int long integer do do cPtr = &c;
float single precision floating point statement; cout << x++ << endl;
double double precision floating point while (expression); while (x < 100);
Use the indirection operator (*) to access or change the
These are the most commonly used types; this is not a do do value that the pointer references.
complete list. { {
statement; cout << x << endl; Example
statement; x++;
Operators } }
// continued from example above
*cPtr = 'b';
The most commonly used operators in order of precedence: while (expression); while (x < 100); cout << *cPtr << endl; // prints the char b
1 ++ (post-increment), -- (post-decrement) cout << c << endl; // prints the char b
2 ! (not), ++ (pre-increment), -- (pre-decrement)
for Loop
3 *, /, % (modulus)
4 +, - Array names can be used as constant pointers, and pointers
can be used as array names.
5 <, <=, >, >= for (initialization; test; update)
6 == (equal-to), != (not-equal-to) {
statement; Example
7 && (and) int numbers[]={10, 20, 30, 40, 50};
statement;
8 || (or) } int* numPtr = numbers;
9 = (assignment), *=, /=, %=, +=, -= cout << numbers[0] << endl; // prints 10
Example cout << *numPtr << endl; // prints 10
for (count = 0; count < 10; count++) cout << numbers[1] << endl; // prints 20
Console Input/Output { cout << *(numPtr + 1) << endl; // prints 20
cout << "count equals: "; cout << numPtr[2] << endl; // prints 30
cout << console out, printing to screen
cout << count << endl;
cin >> console in, reading from keyboard
}
cerr << console error Common cmath Functions
Example:
cout << "Enter an integer: "; Functions abs(n) Returns absolute value of n
cin >> i;
cout << "Input: " << i << endl; Functions return at most one value. A function that does not pow(n,x) Computes n to the power of x
return a value has a return type of void. Values needed by
a function are called parameters. round(n) Returns n to the nearest whole number
File Input/Output
Example (input): return_type function(type p1, type p2, ...) sqrt(n) Computes square root of a n
ifstream inputFile; {
inputFile.open("data.txt"); statement;
statement; cbrt(n) Computes cube root of n
inputFile >> inputVariable;
// you can also use get (char) or ...
// getline (entire line) in addition to >> } fmax(n,x) Takes n and x and returns the largest of the two
...
inputFile.close(); Examples
fmin(n,x) Takes n and x and returns the smallest of the two
int timesTwo(int v)
Example (output): {
int d; exp(x) Returns exponential (Euler's number) e raised to x
ofstream outFile;
outfile.open("output.txt"); d = v * 2;
outFile << outputVariable; return d; log(x) returns the natural logarithm (base-e logarithm) of x
... }
outFile.close();
void printCourseNumber() Structures
{
Decision Statements cout << "CSE1284" << endl; Declaration Example
return; struct name struct Hamburger
if Example } { {
if (expression){ if (x < y){ type1 element1; int patties;
statement; cout << x; type2 element2; bool cheese;
} } Passing Parameters by Value }; };
if / else Example return_type function(type p1)
if (expression){ if (x < y){ Variable is passed into the function but Definition Example
statement; cout << x; changes to p1 are not passed back. name varName; Hamburger h;
}else{ }else{
statement; cout << y; Passing Parameters by Reference name* ptrName; Hamburger* hPtr;
} } return_type function(type& p1) hPtr = &h;
switch / case Example Variable is passed into the function and
switch(int expression) switch(choice) changes to p1 are passed back. Accessing Members Example
{ { varName.element=val; h.patties = 2;
case int-constant: case 0: Default Parameter Values h.cheese = true;
statement(s); cout << "Zero"; return_type function(type p1=val)
break; break; val is used as the value of p1 if the ptrName->element=val; hPtr->patties = 1;
case int-constant: case 1: function is called without a parameter. hPtr->cheese = false;
statement(s); cout << "One";
break; break; Structures can be used just like the built-in data types in
default: default: arrays.
statement; cout << "What?";
} }
Classes Overloading Functions Arrays
Declaration Example Functions can have the same name and same number of 1D array
class classname class Square
parameters of diffrent types //format: dataType arrayName[arraySize]
{ { //Example
public: public: //Takes and returns integers int arr[10]; //array of length 10
classname(params); Square(); int divide (int a, int b)
~classname(); Square(float w); { return (a/b); } // initialising with values
type member1; void setWidth(float w); double arr[5] = {12.5, 1.35, 23, 8.54, 3.55};
type member2; float getArea(); //Takes and returns floats cout << arr[0] << endl; //prints 12.5
protected: private: float divide (int a, int b) cout << arr[3] << endl; //prints 8.54
type member3; float width; { return (a/b); }
private: };
type member4;
}; divide(10,2) //returns 5 2d array (Multidimensional array)
divide(10,2) //returns 3.3333333333 //format: dataType 2dArrayName[][arraySize]
//Example
public members are accessible from anywhere the class is
float arr[][10];
visible.
private members are only accessible from the same class // initialising with values
or a friend (function or class). int arr[2][3] = {{2, 3, 1}, {4, 5, 6}};
protected members are accessible from the same class, Recursion cout << arr[0][2] << endl; // prints 1
cout << arr[1][1] << endl; // prints 5
derived classes, or a friend (function or class).
Functions can call themselves
constructors may be overloaded just like any other
function. You can define two or more constructors as long Example
as each constructor has a different parameter list. double factorial (double n)
{
if (n > 1) Vectors
{ #include <vector>
Definition of Member Functions
return_type classname::functionName(params) return (n * factorial (n-1) 1D array
{ } //format: vector <elementType> vecName
statements; else //Example
{
} vector<int> intList;
return 1;
} // initialising with values
Examples vector<int> intList = {1, 5, 9, 3, 2};
Square::Square() }
cout << intList[1] << endl; // prints 5
{
cout << intList[2] << endl; // prints 9
width = 0; Function Prototyping
} 2d vector (Multidimensional vector)
Functions can be prototyped so they can be used after //format: vector<vector<int>> 2dVecName
void Square::setWidth(float w) being declared in any order //Example
{ vector<vector<int>> vecList;
if (w >= 0) Example // initialising with values
width = w; vector<vector<int>> vecList = {{2, 3, 1}, {4, 5,
else 6}};
// Prototyped functions can be used anywhere
exit(-1); cout << vecList[0][1] << endl; //prints 3
// in the program
} cout << vecList[1][2] << endl; //prints 6
#include <iostream.h>
float Square::getArea()
void odd (int a);
{
void even (int a);
User Defined DataTypes
return width*width;
} enum name{val1, val2, ...} obj_name;
int main
{ Example
... enum days_t {MON,WED,FRI} days;
Definition of Instances Example }
classname varName; Square s1();
Square s2(3.5); void odd (int a) setprecision() function
{
#include <iomanip>
classname* ptrName; Square* sPtr; ...
sPtr=new Square(1.8); } double a = 3.14159;
void even (int a) cout << fixed << setprecision(2) << a; //prints 3.14
Accessing Members Example { cout << fixed << setprecision(4) << a; //prints 3.1415
varName.member=val; s1.setWidth(1.5); ...
varName.member(); cout << s.getArea(); } //the defaultfloat function ensures specific variables are
printed out with the given decimal numbers
ptrName->member=val; cout<<sPtr->getArea();
double a = 3.14159;
ptrName->member(); double b = 2.00;
cout << fixed << setprecision(3) <<"a: " << a << defaultfloat;
cout << " b: " << b << endl; //prints a: 3.142 b: 2

Common Vector Functions (#include <vector>) Common String Functions (#include <string>)
vec.at(index) str.at(index) Returns the element at the position specied by index.
Returns the element at the position specied by index.
vec[index] str[index]

str.append(n, ch) Appends n copies of ch to str, in which ch is a char variable or a char constant.
vec.front() Returns the first element. (Does not check whether the object is empty.)
str.append(str1) Appends str1 to str.
vec.back() Returns the last element. (Does not check whether the object is empty.) str.find(str) Returns the index of the rst occurrence of str in str. If str is not found, the special value string::npos (-1) is returned.
vec.clear() Deletes all elements from the object.
str.find(str, pos) Returns the index of the first occurrence at or after pos where str is found in str.
vec.push_back(elem) A copy of elem is inserted into vec at the end.
str.size() Returns a value of type string::size_type giving the number of characters str.
vec.pop_back() Delete the last element of vec. Returns a string that is a substring of str starting at pos to the end of the str.
str.substr(pos)
vec.empty() Returns true if the object vec is empty and false otherwise. str.substr(pos, len) Returns a string that is a substring of str starting at pos. The length of the substring is at most len characters.
vec.size() Returns the number of elements currently in the object vec. The value returned is an unsigned int value. str.insert(pos, str) Inserts all the characters of str at index pos into str.

vec.max_size() Returns the maximum number of elements that can be inserted into the object vec str.insert(pos, n, ch) Inserts n occurrences of the character ch at index pos into str.

Modified from C++ Reference Card: https://latex4ei.de/ext_downloads/CppRefCard.pdf


Developed for Mississippi State University's CSE1284 and CSE1384 courses

You might also like