1066 字
5 分钟
Study Notes for Beginning C++ (10th Edition)

Written while studying Beginning C++ (10th Edition), this mainly records things I hadn’t noticed or didn’t know before.

I strongly recommend this book. It’s easy to understand, and the techniques it covers are relatively new, making it very suitable for self-learners.

The entire text is typed out by me character by character. To save effort, I’ll appropriately omit some unimportant information (such as which header files to include, since VS gives hints anyway, so I won’t bother writing them).

Chapter 2 C++ Basics#

Escape Sequences#

NameEscape Sequence
Newline\n
Horizontal Tab\t
Bell\a
Backslash\
Double Quote

In addition, C++11 supports raw string literals, which are suitable for situations where many characters need to be escaped. They must begin with R, and the string content must be placed in parentheses, with an additional pair of double quotes outside the parentheses. The following code outputs the string literal “c:\Windows”.

cout << R"(c:\Windows\)";

Formatting Numbers with Decimals#

Link

Chapter 3 More Flow of Control#

Enumeration Types (Optional Reading)#

An enumeration type is a type whose values are defined by a set of constants of type int. An enumeration type is like a list containing a set of declared constants. Within an enumeration type, two or more named constants may take the same int value. If no values are specified, the identifiers in an enumeration type are automatically assigned a set of consecutive values, with the first being 0 and each subsequent constant being the previous value plus 1 - unless one or more enumeration constants are explicitly assigned values.

enum Direction { NORTH = 0, SOUTH = 1, EAST = 2, WEST = 3 }
enum Direction { NORTH, SOUTH, EAST, WEST }
//The two statements above are equivalent.

C++11 introduces a new kind of enumeration, called a strongly typed enumeration or enumeration class. To define a strongly typed enumeration, just add the keyword class after enum.

The Increment and Decrement Operators Revisited#

If ++ comes before a variable, the variable is incremented first, then the value is returned; if ++ comes after a variable, the value is returned first, then the variable is incremented.

Chapter 4 Procedural Abstraction and Functions That Return a Value#

Some Predefined Functions#

NameDescription
sqrtsquare root
powpower (exponent) (arguments and return value are both double)
absabsolute value of int
labsabsolute value of long
fabsabsolute value of double
ceilrounds up
floorrounds down
srandprovides a seed value for the random number generator
randrandom number

Type Casting#

static_cast<TargetType>(expression);
// int to double
static_cast<double>(3);
//the old-style form of type casting
TypeName(expression);
double(3);
//Although it's said to prefer the first form, the second one types fewer characters, so...

Another Form of Function Declaration#

Function declarations do not have to list the parameter names. The following two declarations are equivalent:

double abc(int a, double b);
double abc(int, double);

But you should stick with the first form to ensure readability.

Chapter 5 Functions for All Subtasks#

Call-by-Reference Parameters#

Sometimes they work wonders and are super comfortable to use.

// normal (call-by-value) function declaration
int abc(int a);
// call-by-reference function declaration
int abc(int& a);

Chapter 6 I/O Streams - An Introduction to Objects and Classes#

File I/O#

using namespace std;
ifstream inStream;
ofstream outStream;
inStream.open("infile.dat");
outStream.open("outfile.dat");
inStream.close();
outStream.close();

Appending to a File (Optional Reading)#

ofstream fout;
fout.open("data.txt",ios::app);

Formatting Output with Stream Functions#

Member functions of every output stream (partial):

FlagMeaning
precision()specifies a different number of decimal places
setf()sets flags
width()how many spaces the output item occupies (field width) (used for left/right alignment)

The formatting flags of setf():

FlagMeaning
ios::fixeddoes not use scientific notation
ios::scientificuses scientific notation
ios::showpointshows all trailing zeros after floating-point numbers
ios::showposoutputs a plus sign before positive integers
ios::rightright-aligned
ios::leftleft-aligned

Any flag can be canceled with unsetf().

Manipulators#

FlagMeaning
endlno need to explain this one
setwexactly the same as width
setprecisionexactly the same as precision

These feel pretty redundant…

String I/O#

put(),get(),putback()

Universal Stream Parameters#

Useful for situations where it’s sometimes cin and sometimes an input file stream.

NameKeyword
input streamistream
output streamostream

Default Arguments of Functions (Optional Reading)#

void newLine(istream& inStream = cin);

Checking for the End of a File#

Method 1:

double next, sum = 0;
int count = 0;
while (inStream >> next)
{
sum += next;
count++;
}

Method 2: the eof member function.

Predefined Character Functions#

Omitted

Chapter 7 Arrays#

C++11 Range-Based for Loops#

A new kind of for loop in C++11, used to quickly iterate over array elements.

int arr[]={1,2,3,4,5};
for(auto i : arr)
cout<<i;

You can even do this

int arr[]={1,2,3,4,5};
for(int& i : arr)
i++;
for(int i : arr)
cout<<i;

An Entire Array as a Function Argument#

It’s basically the same as using call-by-reference parameters. To prevent accidental modification, it’s common to use const.

Chapter 8 Strings and Vectors#

Predefined C-String Functions#

FunctionDescriptionNote
strcpy(Target_string,Src_string)copies the value from Src_string into Target_stringdoes not check the maximum capacity that Target_string can store
strcat(Target_string,Src_string)appends the value from Src_string to the end of Target_stringdoes not check the maximum capacity that Target_string can store
strlen(Src_string)returns an integer for the length of Src_string (the null character ‘\0’ is not counted)
strcmp(String_1, String_2)returns 0 if the two strings are equalIf they are equal, it returns 0, which converts to false. Note that this may be the opposite of what you’d expect.

If you need to check the maximum capacity that Target_string can store, you can use functions with a trailing _s, such as strcpy_s.

The Standard string Class#

The getline Member Function#

There are two versions

istream& getline(istream& ins, string& strVar, char delimiter);
istream& getline(istream& ins, string& strVar);

The first version lets you customize the delimiter; the second version defaults to ‘\n’ as the delimiter.

Note: when mixing cin and getline, be careful. cin leaves the ‘\n’ for getline, causing getline to read an empty string.

Member Functions#

ExampleDescription
Element Access
str[i]
str.at(i)

str.substr(position, length)
str,length()

returns a reference to the element at index i, without checking for invalid indices
same as above, but this version checks for invalid indices
returns a substring of the calling object, starting at position and containing length characters
returns the length
Assignment/Modification
str.empty()
str.insert(pos, str2)
str.erase(pos, length)

returns true if str is an empty string, otherwise false
inserts str2 at position pos in str
removes a substring of length length, starting at pos
Search
str.find(str1)

str.find(str1, pos)
str.find_first_of(str1, pos)
str.find_first_not_of(str1, pos)

returns the index of the first occurrence of str1 in str. If str1 is not found, returns the special value string::npos
returns the index of the first occurrence of str1 in str, searching from pos
returns the index of the first occurrence of any character of str1 in str, searching from pos
returns the index of the first character not in str1 in str, searching from pos

Small Details#

Assignment does not work with C-strings, so the following seemingly valid statement is actually illegal.

aCString = stringVariable.c_str(); //illegal

String Conversion#

Functions under C++11 (rolled back from pre-C++11) Convert to numbers stof(does anyone still use float),stod,stoi,stol Convert various weird types to strings to_string

Vectors#

One of my favorite features. It deserves a name, let’s give it one. Who doesn’t like an advanced array that can grow automatically and instantly tells you its length

Chapter 9 Pointers and Dynamic Arrays#

Basic Memory Management#

Remember to delete after you new. Also, after deleting, remember to point the dangling pointer to nullptr.

Study Notes for Beginning C++ (10th Edition)
https://tski.uk/blog/en/c-study-notes/
作者
Tokisaki Galaxy
发布于
2021-03-13
许可协议
CC BY