Chapter 4 Composite Type
0.Before Everything
Before Everything
这是一份四年没有学过C++的菜鸡由于工作岗位需求重拾C++的复习记录,因为工作需要在练习英文,加上Ubuntu下输入法与IDE的冲突,所以写纯英文的笔记,顺便练习一下自己英文的水平,如果有英语的表达不当或者对C++的理解错误,还请看到的大佬提醒我,共勉,谢谢。
4.1 Array
1.Array declaration
//typeName arrayName[arraySize]
short months[12];
Key points:
- The type of data stored in the array.
- The name of the array.
- The size of the array. It must be a constant value.
2.Initialization
Array initialized by a serial of elements wrapped by braces and split by comma. The length of element list must
be shorter than the size defined in declaration, and the default element will be initialized to a default value 0.
If there is not a explicit declaration of size, compiler will count the number of elements in the list(but it’s not safe)
The array initialization is only available when creating an array.
Examples:
int cards[4] = {1,2,3,4};
int arr[4] = {1,2,3}; // the last element will be 0.
int hand[3];
int noSize[] = {1,2,3,4,5,6}; //compiler calculate size as 6
hand = {1,2,3}; //not allowed, use initialization after declaration
hand = cards; //not allowed, can not assign an array to another one
C++11 array initialization:
int noEqual[3] {2,3,4};
int noElem[4] {}; // all element set to 0
long narrow[3] {25, 35, 3.0}; // not allowed, narrowing assignment
4.2 String
1.String in C++
String => a serial of characters stored in mem sequentially.
There are two methods for C++ to proceed string:
1.C-style string
2.C++ string (in string lib)
2.C-style string
C-style string is a char array ended with an empty character (\0)
char notString[] = {'a', 'b', 'c'};
char aString[] = {'a', 'b', 'c', '\0'};
The role of
\0
is to mark the end of string. There are many functions that proceed string in C++.
They proceed string char by char until meet a\0
. If there was no\0
at the end of a char array, those functions will proceed the succeeding data in memory
which is not belong to the string, until next\0
.
There is another form of string declaration:
char bird[11] = "Mr. Cheeps"; //the \0 is understood
char fish[] = "fish"; // compiler will count 5 for the array
A string wrapped by quotations will contain a \0
automatically.
3.The string class
string
is a class provided by header file string, in namespace std.
It requires “using” order or “std::string”.The string class supports any standard input and output including cin and cout.
And it allows using array notation to access any character in it, and using c-style string
to init it.
int main(){
using namespace std;
string myStr = "abc";
cout << myStr << endl;
cout << myStr[2] <<endl; // print c
string cpp11 {"C++ 11 style string"};
string strJoin = myStr + cpp11; // joined string
myStr += cpp11; // append string
}
4.Some operations of string
- strcat and strcpy(C function): Using
strcpy(dest, src)
to copy src to dest. Or usingstrcat(dest, src)
to append src after dest and return a pointer towards dest. - string input: Using
cin >> str
to assign input string to str. Or usingcin.getline(string dest,int length)
orgetline(cin, dest)
to read input to dest string. - string output: Using
cout << str
to read str to output. - raw string: Wrapping string by
R"(
as start and)"
as end, we can use quotations in string instead of using escape character
4.3 Introduction of struct
1.Declaration of struct
struct inflatalbe{
char name[20];
float volume;
double price;
};
2.Using struct in program
struct inflatable{
char name[20];
float volume;
double price;
};
int main(){
using namespace std;
inflatable guest = {
"Gloria",
1.88,
29.99
};
cout << "Name of guest is: " << guest.name << endl;
cout << "Total price: " << guest.price << endl;
}
//===============================================
struct {
char name[20];
float volume;
double price;
}inflatable;
int main(){
using namespace std;
auto guests = inflatable;
guests = {
"Gloria",
1.88,
29.99
};
cout << "Name of guest is: " << guest.name << endl;
cout << "Total price: " << guest.price << endl;
}
4.4 Union
1.What is Union
Union is a data format like struct but can store only one type.
2.Union declaration
union Token{
char cval;
int ival;
double dval;
};
3.Using union
Union’s values are mutually exclusive. The previous value will lose when assign a value to another member.
{
Token token;
token.cval = '1';
token.ival = 1; // cval lost
}
4.5 Enum
The enum is a tool to generate symbol constant value.
The value of enumerators start from 0.
If an enumerator has not been initialized, it will have a default
value = previous value + 1
//red = 0, orange = 1 ...
enum color{
red, orange, yellow, green
};
//Set value of enumerators explicitly
enum bits{
one = 1, two = 2, four = 4, eight = 8
};
4.6 Pointer and free memory
1.Pointer basic introduction.
Core operators:
&
=> get the address of a variable
*
=> use this to define a pointer
int var = 6; //declare a variable
int* p; // declare a pointer to an int
p = &var; //assign address of var to p, the value of p is a hex address
cout << *p << endl; // in fact cout << var
cout << &var << endl; // in fact cout << p
The *
must write before the pointer.
Statement int * p, x
declare a pointer “p” and an int variable “x”.
2.Assign a address to a pointer
int * pt;
pt = 0xB8000000; // mismatch
pt = (int *) 0xB8000000; //type match
3.Using “new” to allocate memory
int *pt = new int; // allocate memory for an int
*pt = 1001; // store a value
4.Using “delete” to free memory
This statement will free memory a pointer refers to, but not the pointer.
delete
only available on a pointer. And it’s safe on a null pointer.
int * pt = new int;
...
delete pt;
5.Using “new” to create a dynamic array.
This statement creates an int array which can store 10 elements. And the operator “new” will
return the address of first element.When we need free the memory, use
delete [] arr
.
int * arr = new int[10];
delete [] arr;
6.Conventions about “new” and “delete”
- Don’t use “delete” to free memory which was not created by “new”
- Don’t use “delete” twice on same memory
- Use “delete []” if the memory of an array which was created by “new []”
- Use “delete” on a null pointer is safe
4.7 “vector” and template array
1.vector
vector is an encapsulation class of dynamic array. It is defined in namespace std.
It can be resized,or append and insert data anytime.
vector<int> vi; //create a zero-size array of int
vector<doble> vd(10); // create a array of double with 10 capability
2.Template array (C++ 11)
array<int, 5> darr;//create an array which can store 5 ints