0% found this document useful (0 votes)
149 views

C++ Cheatsheet

The document describes various string, file stream, and data structure functions in C++. It includes functions for manipulating strings like substr and find. It also shows examples of using file streams, structs, vectors, and recursion.

Uploaded by

code.ayechan
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)
149 views

C++ Cheatsheet

The document describes various string, file stream, and data structure functions in C++. It includes functions for manipulating strings like substr and find. It also shows examples of using file streams, structs, vectors, and recursion.

Uploaded by

code.ayechan
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

Strutils functions

String Member Function Prototypes int atoi(const string & s); // returns int equivalent of string s
string substr(int pos, int len); double atof(const string & s); // returns double equivalent of string s
// precondition: 0 <= pos, and pos < length of the string object string itoa(int n); // returns string equivalent of int n
// postcondition: returns substring of len characters beginning at position string tostring(int n); // like itoa, convert int to string
// pos. Returns as many characters as possible if len is too large, but string tostring(double d); // convert double to string
// causes error if pos is out of range (>= length of the string object) void ToLower(string & s); string LowerString(const string & s);
void ToUpper(string & s); string UpperString(const string & s);
int length(); // postcondition: returns the number of characters void StripPunc(string & s); void StripWhite(string & s);

int rfind(string s); int find(string s);


// postcondition: rfind is same as find, but searches backwards, returns // returns first position/index at which substring s begins in, otherwise returns string::npos
the last occurrence // returns string::npos if s does not occur int find(string s, int pos);
char at(int pos); int rfind(string s, int pos);
// you can change or extract one character of a string // There is another version of find and rfind that takes two parameters
// returns the char at specified pos, causes error if pos is out of range // First parameter is the search string, second parameter is an integer (an pos value)

class Dice Loop Examples File Streams


{ int sum = 0;
public: ifstream input; ofstream out;
int i = 1; string filename = "test.txt";
Dice(int sides); // constructor
int Roll(); // return the random roll while (i <= 10) input.open(filename.c_str()); // bind input to named file
int NumSides() const; // number of sides { if (input.fail() ) { // if filename is invalid
int NumRolls() const; // # times rolled sum = sum + i; cout << "cannot open " << filename << endl;
private: i = i + 1; return 0; // stop program
int myRollCount; // # times die rolled }
}
int mySides; // # sides on die while ( input >> word ) {
int sum = 0; numWords++;
}; for (int i = 1; i <= 10; i++) }
{ input.clear(); // clear the error flags
RandGen(); // constructor sum = sum + i; input.seekg(0); // reset the filepos to the beginning of the file
} while ( ! input.eof() ) // until the end of the file
int RandInt(int max = INT_MAX);
do { int num;
// returns int in [0..max)
{ if ( input >> num )
int RandInt(int low, int max); cout << num << "\tvalid \n";
// returns int in [low..max] cout <<"enter number [0..100] ";
else { // clear the error flags and skip the invalid entry
cin >> num; input.clear(); string s; input >> s;
double RandReal();
// returns double in [0..1) } while (num < 0 || num > 100 ); cout << s << "\tinvalid \n";
double RandReal(double low, }
cin stream – add 10 integers }
double max); // range out.open(filename.c_str(), ios::app); // to append to the end
[low..max] for (count=1; count <= 10; count++) {
if (cin >> num) { out << "CS201 test output file " << endl;
cout << num << " is valid " << endl; for (count=0; count < 10; count++) {
sum += num; out << count +1 << endl;
Builtin Array } out.close(); // output file example
const int MAX_SIZE = 100; }
else { // read file line by line // read file one char at a time
int list[MAX_SIZE];
cin.clear(); string s; int num, total=0; char ch;
int k;
cin >> s; while ( getline(input, s) ) while ( input.get(ch) )
list[0] = list[1] = 1;
cout << "entry is invalid“ << endl; { numLines++; { numChars++;
for (k=2; k < MAX_SIZE, k++)
} istringstream ssLine(s); if ( ‘\n’ == ch)
{
} ssLine >> name >> lname; numLines++;
list[k] = list[k-1]+list[k-2]; while ( ssLine >> num ) else if ( ‘\t’ == ch)
} total + num; numTabs++;
Struct } }
Matrix struct student
vector<vector<int>> mat(3, vector<int>(5)); {
for (int j=0; j < mat[0].size(); j++) { unsigned int id; char data type char digitch = ‘3’;
int sum = 0; string name, lastname; cout << "\"\\\n\"\"\n\\"; int digitnum = digitch - '0';
for (int k=0; k < mat.size(); k++) { double gpa; char toupper (char ch) {
sum += mat[k][j]; }
if (ch >= 'a' && ch <= 'z') // if lowercase
} student stu; stu.name = "Ali";
cout << stu.gpa; return ch + ('A' - 'a'); // return its uppercase
cout << "sum of column " << j << " is "
<< sum << endl; vector<student> class(11); return ch; // otherwise return parameter unchanged
} class[1].gpa = 3.2; }
Robot Member Function Prototypes void ShowMessage (string message); Recursion
enum Direction { east, west, north, south }; void ShowMessage (int message); double Power(double x, int n)
enum Color { white, yellow, red, blue, green, purple, pink, orange }; void GetInput(string prompt, string & var); // post: returns x^n
class Robot void GetInput(string prompt, int & var); {
{ int GetThingCount(int x1,int y1, int x2, int y2); if (n == 0)
public: int GetCellCount (int x, int y); return 1.0;
Robot (int x, int y, Direction dir = east, int things = 0); void PutThings(int xCor, int yCor, int thingCount);
// robot constructor - color yellow, direction is east and bag count is 0 return x * Power(x, n-1);
}
void Move (int distance = 1); // to move robot, default is 1
void TurnRight (); // to turn the robot right Binary Search
void SetColor (Color color); // to change the color of robot int bsearch(const vector<string> & list,
bool FacingEast(); // to check if robot is facing east const string & key)
bool FacingWall(); // to check if robot is facing wall {
bool Blocked(); // to check if robot is blocked by another robot Member Function Examples int low = 0;
bool PickThing (); // take an item to the bag from current cell int Robot::GetXCoordinate() int high = list.size()-1;
bool PutThing (); // put an item to the current cell from bag { int mid;
bool CellEmpty (); // check if the cell is empty return xPos; while (low <= high) {
} mid = (low + high)/2;
bool BagEmpty (); // check if the bag is empty
if (list[mid] == key) // found
private: void Robot::Turn(Direction dir)
return mid;
int xPos; //x coordinate of the location of robot {
else if (list[mid] < key) //upper
int yPos; //y coordinate of the location of robot if (stalled == false) low = mid + 1;
Direction direction; //current direction of robot { else // key in lower half
Color color; //current color of robot direction = dir; high = mid - 1;
int bag; //current # of things in the bag of robot theRobotWindow- }
bool stalled; //true if the robot is dead >Redraw(this); return -1; // not in list
bool visible; //true if the robot is visible } }
}; }

The Class Date Vectors


class Date vector<int> randStats(7); RandGen random;
{ for(k=0; k < n; k++) // pick all random numbers
public: { num = random.RandInt(7); // between 0 and 6
// constructors randStats[num] = randStats[num] + 1;
Date(); // construct date with default value }
Date(long days); // construct date from absolute # vector<double> d(10, 3.14); // 10 doubles, all pi
Date(int m,int d,int y); // construct date with specified values vector<string> words(10); // 10 strings, all ""
vector<Date> holidays(6); // 6 today’s dates
int Month() const; // return month corresponding to date
int Day() const; // return day corresponding to date void Count (vector<int> & counts); void Print(const vector<int> & counts);
int Year() const; // return year corresponding to date vector<int> Count (istream & input, int & total); // return from a function
int DaysIn() const; // return # of days in month vector<string> words; //create empty vector
string DayName() const; // "monday", "tuesday", ... "sunday" while (input >> w) {
string MonthName() const; // "january","february",... "december" words.push_back(w); //adds the next word to the vector
long Absolute() const; // number of days since 1 A.D. for date //also increases the capacity if necessary
string ToString() const; // returns string for date in ascii }
int DaysRemaining() const; // return # of remaining days in month void collect(const vector<string> & a, vector<string> & matches)
{ int k; // matches contains all elements of a with first letter 'A'
Date operator ++(int); // add one day, postfix operator for (k=0; k < a.size(); k++) {
Date operator --(int); // subtract one day, postfix operator if (a[k].substr(0,1) == "A")
Date& operator +=(long dx); // add dx, e.g., jan 1 + 31 = feb 1 matches.push_back(a[k]);
Date& operator -=(long dx); // subtract dx, e.g., jan 1 - 1 = dec 31 }
void SetYear(int); }
private:
int myDay; // day of week, 0-6
int myMonth; // month, 0-11 Selection Sort Insertion Sort
int myYear; // year in four digits, e.g., 1899 void SelectSort(vector<int> & a) void InsertSort(vector<string> & a) {
}; { int k,loc, numElts = a.size();
int j, k, temp, minIndex, numElts = a.size(); for(k=1; k < numElts; k++)
for(k=0; k < numElts - 1; k++) {
Recursion { minIndex = k; // min element index string hold = a[k]; // insert this element
int RecursFibonacciFixed(int n) for(j=k+1; j < numElts; j++) loc = k; // location for insertion
{ // Fixing recursive Fibonacci { if (a[j] < a[minIndex]) // shift elements to make room for hold
static vector<int> storage(31,0); { minIndex = j; // new min index
while (0 < loc && hold < a[loc-1])
if (0 == n || 1 == n) return 1; }
else if (storage[n] != 0) return storage[n]; {
}
else { a[loc] = a[loc-1];
temp = a[k]; // swap min and k-th
storage[n] = RecursFibonacciFixed (n-1) + a[k] = a[minIndex]; loc--;
RecursFibonacciFixed (n-2); a[minIndex] = temp; }
return storage[n]; } a[loc] = hold;
} } }
} }

You might also like