0% found this document useful (0 votes)
43 views5 pages

Cheat Sheet CS 31 Final

This cheat sheet provides a comprehensive overview of C++ programming concepts, including variable declarations, control structures, string manipulation, arrays, pointers, and memory management. It covers key functions and methods, such as string comparisons, conversions, and dynamic memory allocation, along with examples and common pitfalls. Additionally, it highlights the differences between C and C++ regarding strings and pointers, as well as the importance of constructors and destructors in class management.
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)
43 views5 pages

Cheat Sheet CS 31 Final

This cheat sheet provides a comprehensive overview of C++ programming concepts, including variable declarations, control structures, string manipulation, arrays, pointers, and memory management. It covers key functions and methods, such as string comparisons, conversions, and dynamic memory allocation, along with examples and common pitfalls. Additionally, it highlights the differences between C and C++ regarding strings and pointers, as well as the importance of constructors and destructors in class management.
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/ 5

Cheat Sheet - CS 31

常用语句 int char[10] = “hello”; //自动设 char[5] = ‘\0’, 以及后面 4 个=‘\0’


(?)
#include <iostream> array is default passed by reference.
#include <string>
#include <cctype>
#include <cstring> Char
using namespace std; #include <cctype>
int main() isdigit(ch) ‘0’ ‘1’ ‘2’ … ‘9’
cin.ignore(10000, ‘\n’); //[前一个
//[前一个 cin numbers,现在想
numbers,现在想 input string] islower(ch) ‘a’ ‘b’ ‘c’ … ‘z’
用来清除以回车结束的输入缓冲区的内容,消除上一次输入对下一次输入的 isupper(ch) ‘A’ ‘B’ ‘C’ … ‘Z’
影响 isalpha(ch) ‘a’ ‘A’ ‘b’ ‘B’ … ‘z’ ‘Z’
cout.setf(ios::fixed); isalnum(ch) = isalpha() || isdigit()
cout.precision(2); string.size()
static_cast<double>(total)/nscores ==> 两个 int 转换为 double if (! isupper(s[]))
循环
【For】 toupper(ch)
for (initialization ; stay-in-loop-condition; prepare-for next-iteration) tolower(ch)
statement toupper(string)//报错!!
string s =“hello”;
for (int k=0; k != s.size(); k++)
转换
cout <<s[k]<<endl;
【char into int】
char x = '2';
for (int i = 0, x = strlen(input); i < x; i++) { int y = (x-'0') * 2;
input [i] = toupper(input[i]);
【char into string】
For 可以写在一起: char arr[ ] = "This is a test";
for (sum = 0, n = 1; n <= 10; sum = sum + n, n++); string str(arr);
??
【While】
do 【substr(startIndex, length) method】
{ cout << "Hello "; string sub = x.substr(3, 2);
countDown = countDown - 1;
} while (countDown > 0);
比如说 n=3 【String to Int】
那么 n++就是执行这次循环之后 n=4,本次循环 n=3 string number = "125"; // or let the user cin their own string
++n 执行本次循环前 n 先自加,也就是本次循环 n=4 - do int result = 0;
Example int multiplier = 1;
int count=3; for (int i = number.size() - 1; i >= 0; i--) {
while (count-- > 0) result += (number[i] - '0') * multiplier;
cout <<count<< " "; multiplier *= 10;
//2 1 0
==> 【int to string】
int cout =3; to_string(int)
while (count > 0)
count - -; //or - - count
cout << count << “ “; 【int to char】
//2 1 0 char a = 2+’0’

int count2 =3; 【int to double】


while (--count2 > 0) static_cast<double>(total) // temporary convert integer to double
cout<< count2<< " ";
cout << endl;
//2 1
Break & Continue
String
break == 跳出这个 loop #include <string>
continue == ignore 之后的所有 从循环的最初开始 (for: index +1; while: depends) string s = “Hello”;
cout<<s.size(); ==> writes 5
Scoping //s.length()一样
所有的变量只存在在属于他们的{ }里 cout<<s[4]; ==>writes o
Variables declared outside the function do not exist inside the function s[6]; ==> Undefined behavior
unless they are global variables cin.ignore(10000, ‘\n’) [前一个 cin numbers,现在想 input string]
Substring:
Array string s = “duplicate”;
a[k] a sub k // means the character at position k of a s.substr(5,3); //writes cat
s.size() // s.length == the number of characters in the string
int a[5] = {}; //每一个设值为 0;
Compare String
Cheat Sheet - CS 31
Ghostwriter < Ghoul (s has a lower value than u, b/c s is early than using namespace std;
u) //the length of string is irrelevant; only find the first mismatch and int main() {
compare the alphabetical order int i = 0;
不可以的用法 do {
int arr[]; // Size not included. for(int j = i ; j >= 0 ; j-- )
/****** Use of non-const variable. ******/ cout << "*" ;
int x; cout << endl;
cin >> x; i++; }
char buffer[x]; while(i<4); //注意分号!
}
*
c string **
初始化
***
char shortString[] = "abc"; 等于 char shortString[4] = "abc";char
****
shortString[] = "abc";不等于 char shortString[] = {'a', 'b', ‘c’};//不
自动加’/0’
不能 char string1[variable], 【Switch】
read in a c string: The value tested must be an integral type (e.g. int, char, short, long, etc.) not
cin.getline(s,100); //string no more than 100 characters, 要 string.
int main() {
包括’\0’。
int i = 0,value = 0;
// throw away newline for( i = 0 ; i < 5 ; i++ )
s = t; // Error! Arrays can not be assigned;
{ switch( i ) {
<cstring> case 1: value = i + 1;
strcpy(s, t); // strcpy(destination, source) case 2: value = value - 1;
strcat(s, “!!!”); // now s is “Ghost!!!” case 4: value = value + 2; break;
strcmp(s, t); default: value = value + 1;}
应用 if (strcmp(a, b) < 0); if (strcmp(a, b) == 0) }
long length = strlen("dobedo") ; 不要“int”! cout << value << endl; }
char a[MAX_CHAR+1]; //末尾留给’\0’, 否则溢出

【Digits sum of Int】


string s=“Hello"; for (int i = 1; i < to_string(number).length(); i++)
f(s);//won't compile! s is a C++ string, not a C string {
f(s.c_str());//OK
sum += (number/(10^i))%10;
char t[10]=“Ghost";
s=t;//s is now Ghost }
s=“Wow"; return sum
r=s;//won't compile
t=s.c_str();//won't compile
N-dimensional array
strcpy(t,s.c_str());//t is now Wow
double meanForADay(const a[][NWEEKS], int nRows, int dayNumber) //
except for the first array, it has to know how many entries are in the following
判断
arrays
非零即 true,零即 false
if(‘\0’) //为 false
if(‘a’); //为 true int countLength(const char a[][MAX_WORD_LENGTH+1], int n, int
if(“abc”); if (“\0”); //为 true targetLength)
【tips】 {int total = 0;
char aString[10]; for (int k=0; k<n; k++)
aString = "Hello"; {if (strlen(a[1]) == targetLength)
不要随意修改 ’\0’,改了就不是 cstring 了。 total++;}
‘\0’ 和 0 一样,因为它 ascii value 就是 0。 return total;}
注意第二层循环的条件要看着第一层的变化,不要溢出。
long length = strlen(str); void eraseChar(char str[], char c){
int i =0; int x = 0;
while (i<length){ while(str[x] != ‘\0’){
if (str[i] == c)
{
if(str[x]==c){
for (int k=0;k<length-i;k++) for(int y = x;str[y]!=0;y++)
str[i+k]=str[i+k+1];
} str[y] = str[y + 1];
else else
i++;}
x++;}
}
Case Examples
#include <iostream> 同时循环
#include <string>
Cheat Sheet - CS 31
void solvePuzzle( char encodedMsg[] ,char decodedMsg[] ) { delete[] ptr;
int i, j; ————————————-
for(i=0, j=0 ; i < strlen(encodedMsg) ; i+=2, j++) decodedMsg[j] = double b = 9.1;
encodedMsg[i]; double *p = &b;
decodedMsg[j] = 0; double* q; // *q = 4.6; undefined behavior, q. // is uninitialized
} *q = &b;
需要注意的: We are allowed to compare the pointers (AKA the address)
1. 用 bool 判断 loop 之后 记得 set 回原来的 true/false
2. parameter 里带& 传引用 main 里面要 input 一个变量
3. c string: char a[] 不可以直接用等号 assign 一般是每个 character 逐一 assign =============traverse arrays======================
所有的 strcpy, strcat, strcmp 里面的两个 parameter 都要是 c string 不能是 string/charact const int MAXSIZE = 5;
er double da[MAXSIZE];
4. 在给一个新的 c string 赋值之后 记得把它最后一位 set 成 0//‘\0’ for(intk = 0; k < MAXSIZE; k++)
5. 认真审题!看清楚要 set 什么 return 什么 最后记得好好 test da[k] = 3.6;
6. 好好检查 不要出 out of bounds error 尤其是循环里有+1//-1 之类的
Traverse arrays only use MAXSIZE
double* dp;
Pointer for(dp = da; dp < da + MAXSIZE; dp++)
*dp = 3.6;
arr = &arr[0]
*&x ==> x
&a[i] + j ==> &a[i+j] Example of for loop using pointers:
&a[i] - j ==> &a[i-j] const char* findTheChar(const char* str, char chr){
&a[i] < &a[j] ==> i < j for ( ; *str != 0; str++)
a = &a[0] if (*str == chr)
p[i] = *(p+i) return str;
return nullptr;}
const string a[]
= const string* a 【Tips】

&a[0] + 2 = &a[2] 1. define another pointer to an array and use dereferencing to set value
2. *ptr + 3 != *(ptr+3)
2 = &a[2] - &a[0]
&a[0] = &a 3. function 里改变 pointer 要用&。
Class
an object the name of
C++11 and later: nullptr of some . a member of
c and c++: NULL struct type that type

int* p1; a pointer to the name of


int* p2 = nullptr; an object of -> a member of p->m equals to (*p).m
... *p1 ... ==> undefined behavior! p1 is uninitialized some struct that type
... *p2 ... ==> undefined behavior! p2 has the null pointer value type
//it's always gonna crash!
a struct can contain another struct.
【new】
be used to create dynamic variables. The scope resolution operator(::)
these variables can be accessed using pointers. members in struct is public by default;
e.g. members in class in private by default.
string *p;
p = new string;
p = new string(“hello”); encapsulation
accessor mutator
Struct comes from C, which has only structs and no member functions
【delete】
The delete operator eliminates dynamic variables.
【Constructor】
delete leads to dangling pointer
be defined inside or outside of a class, just like normal functions;
delete p;
cannot be called with the dot operator;
Note: Pointer p is now a dangling pointer! Dereferencing it is dangerous and
default constructor is one with no arguments. (leave vars uninitialized)
leads to undefined behavior.
One way to avoid this is to set p to NULL after using delete.
after define the Person::Person(), we can only call it by:
Person p1;
[Dynamic arrays]
p1 = Person(); //ok
int* ptr; Person pa(); // Problem.
int arraySize;
cin >> arraySize;
all forms of constructor cannot be called after the class is declared?
ptr = new int[arraySize];
Cheat Sheet - CS 31
【Destructor】 13.一个 class 里创建另一个 class 要用 new class2()。
A destructor is a member function that is called automatically when an 14.看清楚 class 里的 member 是不是 pointer,如是,用 —>。
object of a class passes out of scope
the destructor should use delete to eliminate any dynamically allocated 15.if (a=b); == a=b; if(a); //所以赋值 and 看是不是 b==0.
variables created by the object 16.pointer++的次数和*pointer 赋值要分别看清。
a default destructor will not delete the dynamic variable created by “new”. 17.看清是>还是>=
18.
Person::Person(){

Fluffy = new Pet(“Steve”);
} [Example]
Pet::~Pet(){ 1. 查重合字母 (ascii 表法)
delete fluffy; bool isFromMagazine(const string magazine, const string message) {
} int magLetters[256];
int mesLetters[256];
// Create character count of each letter beside spaces.
【arrow operator ->】 for (int i = 0; i < magazine.size(); i++) {
be used to access an object’s member variables and functions. if (magazine[i] != ' ')
magLetters[magazine[i] - '\0']++;
function overloading }

for (int i = 0; i < message.size(); i++) {


【const】 if (magazine[i] != ' ')
all-or-nothing proposition mesLetters[message[i] - '\0']++;
function pass by const reference: (not cheap to copy) (const Employee& e) }
Function pass by value: (cheap to copy) // Check to see if we have sufficient letters
(Employee e) for (int i = 0; i < 256; i++)
Caller’s object should change pass by [no-constant] reference if (mesLetters[i] > magLetters[i]) return false;
————————— return true; }
const Zurt* zp = &z; //pointing to 的 value 是 const,不是 pointer。
int const* a = const int* a; // a 不能变
int *const a; // pointer 不能变 2.Pointer 排序法(Sorting //从大到小排列
const int* == int const* void descSort(int* nums, int len) {
for (int x = 0; x < len; x++) {
const int * const == int const * const
int max_num = *(nums + x);
int max_ind = x;
【nullptr】 for (int y = x + 1; y < len; y++) {
nullptr 只能是 pointer != nullptr int curr_num = *(nums + y);
value == a value that a pointer can hold that is guaranteed if (curr_num > max_num)
not to point any values in the program { max_num = curr_num;
max_ind = y;}
int* p2 = nullptr; // follow p2 == undefined behavior }
*(nums + max_ind) = *(nums + x);
use a pointer in for loop: *(nums + x) = max_num; }
for (Employee* ep = company; ep<company +nEmployees; ep++) }
//company is an array of employees
cout<<ep->name<<endl; 3. Reverse an array
void reverse(char *arr)
{ // Initialize a pointer to point to the last char before \0
you can overload a function name if the functions differ in the number or the
char *first = arr;
types of parameters
char *second = arr;
while (*second != '\0')
Tips second++;
1. 注意排除%0 和/0,尤其是循环里; second--;
while (second > first)
2. ‘\0’ only in c string, NOT IN OTHER TYPE OF ARRAY { int temp = *first;
3. Switch 里各个 case 和 default 相通,且只能定义一次 *first = *second;
*second = temp;
4. A reference to a variable is passed to the function instead of a copy of second--; first++; }}
the variable
5. 注意 char-‘0’,不是 char-0。
Tips:
6. class 里重名的 variable,用 this-> 1.Constructor 里可以调用其他的 member function 2.审题 看清有多少 data
7. 在一个 member function 里 class 被 call members 并充分利用 3.pointer 的“*”只在 declare 的时候说明,之后调用
8. constructor and 清理 function 时,调参数(m_amount=0;) pointer//array//function 都不要加这个星号【function 的*加在 return type 旁
9. 所有 constructor 和 destructor 都不能被 call。 边】 4.自己写 class 的时候 分清楚每一个 data type 的类型 尤其:int 还是
10.不能多 delete;所以 new 多少 delete 多少 double?pointer 还是 array 还是 array of pointers? 5.Destructor 只需要管
11.常值的边界。&&mon>=0 && mon < m_money dynamically allocated pointer 别的值不需要 reset(?) 6.选择题问一堆
code 做什么 先从 main 开始看 把数往 function 里带 7.if 判断句里看清双等号
12.for 循环找字母等别忘 break。(bool 和 break 组合使用法) 还是 单等号 8.如果自己创建了一个 new string 记得在最后加 0 bite 9.在 c
Cheat Sheet - CS 31
string 自带的 function 里 original c string name+i 可以表示一个 c string,从 i p.addToy();
开始 p.addToy();}
10. 注意排除%0 和/0,尤其是循环里
Example of object and pointer:
class Fan {public: void turnOn();};
class Rock { public: double weight() const;};
class Robot
{private:
Fan m_cooler; // every Robot must have a fan; fan doesn’t exist if
robot doesn’t exist [directly contained]
Rock* m_rock; //every robot may or may not have a rock};
void Robot::blah()
{ if (m_rock != nullptr && m_rock->weight() >= 50)
m_cooler.turnOn(); //m_cooler is an object but not a pointer to
an object}

Example of this and an array of pointers:


class Company;
class Employee
{public:
Employee(string nm, int a, double sal, Company* cp);
void hire(string nm, double sal, int a);
void giveBonuses() const;
private:
string m_name;
double m_salary;
Example of Destructor:
int m_age;
class Pet
Company* m_company;};
{public:
class Company
Pet(string nm, int initialHealth)
{public:
private:
Company();
string m_name;
~Company();
int m_health;
void hire(string nm, double sal, int a);
Toy* m_favoriteToy;};
private:
Pet::Pet(string nm, int initialHealth)
double m_bonusRate;
{ m_name = nm;
Employee* m_employees[MAXEMPLOYEES];
m_health = initialHealth;
int m_nEmployees;};
m_favoriteToy = nullptr;}
void Company::hire(string nm, double sal, int a)
Pet::~Pet()
{ m_employees[m_nEmployees] = new Employee(nm, a, sal,
{delete m_favoriteToy;}
this);
void Pet::addToy()
m_nEmployees++;}
{ delete m_favoriteToy;
void Company::giveBonuses() const
//防止 f 里面两遍 addToy,create 两个 new
{for (int k = 0; k < m_nEmployees; k++)
m_favoriteToy = new Toy;}
m_employees[k]->receiveBonus();}
void f(string s)
{ Pet p(s, 10);

You might also like