C++-intro
C Basics
What C++ brings:
- Almost all the aspects of C are preserved
- New features are added, e.g., templates, references
- Sophisticated programs are easier to code, thanks to OOP
- C++ is almost a superset of C
new data types:bool a = false, b = true;
new headers:new I/O style:1
2
using namespace std; - input:
cin >> x - output:
cout << 'string' - formatting output:
setw(int width): set the width of the outputsetfill(z): set up the prefix (前缀) of the outputsetprecision(2): set up the precision of the output
pointers for C++
No more malloc, calloc and free:
- Memory for a variable:
int *p = new int; - Memory for an array:
int *p = new int[10]; - Array size can be a variable (not recommended in C)
- Return
NULLon failure (nullptrin mordern C++) - Release the memory:
delete pordelete[] p - pass-by-reference is an additional way to pass an address into a function
strings
1 |
|
other string operations:
1 | string demo = "VG101"; |
String operations (insert, erase, repllace, swap, copy, finnd, substr)
File I/O
Requires header: #include <fstream>
- Open file for reading:
ifstream in; in.open("file.txt"); - Open file for reading in short:
ifstream in("file.txt") - Read from a file:
inused in the same way ascin - Open a file for writing:
ofstream out("file.txt") - Write in a file: out used in the same way as
cout - Read from a file, line by line, into a string s:
getline(in,s)
OOP
object-oriented programming
A new approach:
- Everything is an object
- Objects communicate between them by sending messages
- Each object has its own type
- Object of a same type can receive the same message
object
two main components:
- Its behavior, what can be done with it, its methods
- The data it contains, what it knows, its attributes
Class
Defines the family, type or nature of an object
Equivalent of the type in “traditional programming”
visibility
Private or public:
- Private members can only be accessed by member functions within the class
- Users can only access public members
example:1
2
3
4
5
6
7
8
9
10class Circle {
/* user methods (and attributes) */
public:
void move(float dx, float dy);
void zoom(float scale);
float area();
/* implementation attributes (and methods) *+*/
private:
float x, y, r;
};
implementation
Getting things ready:
- Class interface is ready
- Instantiation is possible
- Does not compile: no implementation of the class yet
- Syntax: classname::methodname
example:1
2
3
4
5
6
7
8
9
10
11
12
13
const float PI=3.1415926535;
void Circle::move(float dx, float dy) {
x += dx;
y += dy;
}
void Circle::zoom(float scale) {
r *= scale;
}
float Circle::area() {
return PI
}
constructor
A constructor is a member function/method with the following properties:
- If a class has a constructor, a constructor is called automatically whenever an instance of the class is declared.
- The name of a constructor must be the same as the name of the class.
- A constructor does not have any return value. void or other return type all not allowed.
example:1
2
3
4
5
6
7
8class Circle {
public:
int x, y;
Circle(){
x = 1;
y = 1;
}
}
this
Methods access the object on which they were called through an extra, implict parameter named this, which is initialized with the address of the object on which the method was invoked
Instance
Realisation of an object from a given class
Equivalent of a variable in “traditional programming”
overload
definitions:
- Two constructor defined: circle() and circle(float)
- Proper one automatically selected
inheritance
Private inheritance:
- Default type of class inheritance
- Any public member from the base class becomes private
- Allows to hide “low level” details to other classes
Therefore,protectedburn.
Protected members: - Compromise between public and private - They are available to any derived class
- No other class can access them
friend: bypass all this security of the class
avoid using it!!
virtual
Sometimes we have to create a pointer to the base class that refers to all the derived objects. When the base class pointer contains the derived class address, the object always executes the base class function.
Therefore, virtual born to address the drawback.
- Virtual function in the base class
- Function can be redefined in derived class
- Preserves calling properties
example:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using namespace std;
class Cow {
public: Cow(int f=0){grass=f;}
virtual void Speak () { cout << "Moo.\n";}
void Eat() { if(grass > 0) { grass—— ; cout<< "Thanks I’m full\n";}
else cout << "I’m hungry\n";}
protected: int grass;
};
class SickCow : public Cow {
public: SickCow(int f=0,int m=0) {grass=f; med=m;}
void Speak () { cout<< "Ahem... Moo.\n";}
void TakeMed() { if(med > 0) { med--; cout<< "I feel better\n";}
else cout << "I’m dying\n";}
private: int med;
};
int main () {
Cow cl; SickCow c2(1); Cow »c3=&c2;
c1.Speak();c1.Eat();c2.Speak();c2.TakeMed();c3->Speak();
}
more from classes: STL
std::vector
std::vector是一个动态数组,提供了许多方便的操作来管理动态大小的数组。
常用操作
创建和初始化
1
2
3
4
std::vector<int> vec; // 创建一个空的 vector
std::vector<int> vec(10); // 创建一个包含 10 个元素的 vector,初始值为默认值 0
std::vector<int> vec(10, 5); // 创建一个包含 10 个元素的 vector,初始值为 5添加元素
1
2vec.push_back(1); // 在末尾添加元素
vec.emplace_back(2); // 在末尾就地构造元素(C++11)访问元素
1
2
3
4int val = vec[0]; // 使用下标访问(不进行边界检查)
int val = vec.at(0); // 使用 at 方法访问(进行边界检查)
int first = vec.front(); // 获取第一个元素
int last = vec.back(); // 获取最后一个元素删除元素
1
2
3vec.pop_back(); // 删除最后一个元素
vec.erase(vec.begin() + 1); // 删除指定位置的元素
vec.clear(); // 清空所有元素大小和容量
1
2
3
4size_t size = vec.size(); // 获取元素个数
size_t capacity = vec.capacity(); // 获取当前容量
vec.reserve(20); // 预留空间,至少可以存储 20 个元素而不重新分配内存
vec.resize(15); // 调整大小,如果增大,则新元素初始化为默认值迭代器
1
2
3for(auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int main() {
std::vector<int> vec = {5, 2, 9, 1, 5, 6};
// 使用 std::sort 进行升序排序
std::sort(vec.begin(), vec.end());
std::cout << "Sorted vector: ";
for(int v : vec) {
std::cout << v << " ";
}
std::cout << std::endl;
return 0;
}
std::string
std::string是一个专门处理字符串的类,提供了许多方便的操作来管理和操作字符串。
常用操作
创建和初始化
1
2
3
4
5
std::string str; // 创建一个空字符串
std::string str("Hello"); // 使用 C 字符串初始化
std::string str(10, 'a'); // 创建一个包含 10 个字符 'a' 的字符串访问和修改字符
1
2
3char ch = str[0]; // 使用下标访问(不进行边界检查)
char ch = str.at(0); // 使用 at 方法访问(进行边界检查)
str[0] = 'H'; // 修改字符连接字符串
1
2
3
4std::string str1 = "Hello";
std::string str2 = "World";
std::string str3 = str1 + " " + str2; // 字符串连接
str1 += " World"; // 追加字符串查找和替换
1
2
3
4size_t pos = str.find("lo"); // 查找子串,返回第一个匹配的位置
if (pos != std::string::npos) {
str.replace(pos, 2, "LL"); // 替换子串
}子串
1
std::string substr = str.substr(0, 5); // 获取子串,从位置 0 开始,长度为 5
大小和清空
1
2
3size_t len = str.size(); // 获取字符串长度
str.clear(); // 清空字符串
bool isEmpty = str.empty(); // 判断字符串是否为空迭代器
1
2
3for(auto it = str.begin(); it != str.end(); ++it) {
std::cout << *it << " ";
}拆分字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
std::vector<std::string> split(const std::string &s, char delimiter) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(s);
while (std::getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
int main() {
std::string str = "Hello,world,this,is,C++";
char delimiter = ',';
std::vector<std::string> tokens = split(str, delimiter);
std::cout << "Split strings: " << std::endl;
for (const auto &token : tokens) {
std::cout << token << std::endl;
}
return 0;
}
