文章目录
由于专业课选课失败,老师上课不咋讲课,按着书和慕课自学……
string
和C的区别
C++的字符串在C的基础上进行了扩充,在引入了保留字“string”的基础上,承认字符串间赋值、运算合法。
char charr1[20];
char charr2[20] = "string_C";
string str1;
string str2 = "string_Cpp";
charr1 = charr2; // Invalid
str1 = str2; // Valid
string str3;
str3 = str1 + str2; // Valid
str3 += "ZJU" // Valid
字符串的输入
正常的cin与C语言一样接受输入直到空格为止。
面向行的输入
cin.getline(name, n); // 读取(n-1)个字符至name字符串中
cin.get(name, n); // 会将换行符读入到字符串中并保留
cin.get(name, n).get() // 读入两次字符串(有换行符)。
之所以可以这样做,是因为cin.get()函数会返回一个cin的对象。
Reference
type& rename = name;
变量rename即为name,引用在绝大多数情况下需要赋初始值,但在传入函数参数时可以默认为自动赋初始值,引用可以实现在函数内部更改参数的值。
void f(int &a){
cout << "in f() " << a << endl;
a = 30;
cout << "in f() " << a << endl;
}
int main() {
int i = 10;
cout << "in main " << i << endl;
f(i);
cout << "in main " << i << endl;
return 0;
}
// 输出为
// in main 10
// in f() 10
// in f() 30
// in main 30
而如果修改main函数为
int main(){
int i = 10;
f(3 * i);
return 0;
}
程序会报错,这是由于f函数需要的是一个引用的变量,而非值。
:: resolver
void S::f(){ // f is a member function of calss S.
::f(); // Visit a global function.
::a++; // a is a global variable.
a--; // a is a member variable of class S.
}
Definition of a class
- In C++, separated .h and .cpp files are used to define one class.
- Class declaration and prototypes in that class are in the header file (.h).
- All the bodies of these functions are in the source file (.cpp).
STL (Standard Template Library)
Containers
- Vector (expandable array)
- Deque (expandable array, expand at both ends)
- List (double-linked)
- Sets and Maps
Vector
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> x;
for (int i = 0; i < 100; i++){
x.push_back(a);
}
vector<int>::iterator p;
for (p = x.begin(); p < x.end(); p++){
cout << *p << endl;
}
return 0;
}
Basic Vector Operation
// Constructors
vector<Elem> c;
vector<Elem> c1(c2); // 基于c2构建c1
// Simple Method
V.size();
V.empty();
==, !=, <, >, <=, >=;
V1.swap(V2);
// Iterators
I.begin();
I.end();
// Element Access
V.at(index); == V[index];
V.front();
V.back();
// Others
V.push_back(e);
V.pop_back();
V.insert(pos, e);
V.erase(pos);
V.clear();
V.find(first, last, item);
List
As it is double linked, it has more operations than vector:
x.push_front(item);
x.pop_front(item);
Maps
Maps are collection that contain pairs of values.
Pairs consist of a key and a value.