C++

Kaleido Lv4

IO处理

读取char

  1. 读入一个非空白符

    1
    2
    char c;
    cin >> c;
  2. 读入一个字符(包含空白符)

    1
    2
    char c;
    cin.get(c);
  3. 读取未知个数的字符(包含空白符)

    1
    2
    3
    4
    char ch;
    while(cin.get(ch)) {
    ...
    }

读取string

  1. 以空白字符或EOF作为结束标志

    1
    cin >> s;
  2. 以换行符或指定字符作为结束标志

    1
    2
    getline(cin, s);       // 以换行符为结束标志
    getline(cin, s, ','); // 以','为结束标志
1
2
3
4
5
6
7
8
9
10
11
12
13
14
vector<string> split(string s, char c) {
vector<string> vec;
string temp;
for(char ch : s) {
if(ch != c) {
temp += ch;
} else {
vec.push_back(temp);
temp = "";
}
}
vec.push_back(temp);
return vec;
}

指针与常量

1
2
3
4
5
int x;
int * p1 = &x; // 指针可以被修改,值也可以被修改
const int * p2 = &x; // 指针可以被修改,值不可以被修改(const int)
int * const p3 = &x; // 指针不可以被修改(* const),值可以被修改
const int * const p4 = &x; // 指针不可以被修改,值也不可以被修改

指针函数与函数指针

指针函数 Function Pointer

函数指针 Pointer to Function

示例 1:使用函数指针进行排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool compareInt(int a, int b) {
return a < b;
}

bool compareString(const std::string& a, const std::string& b) {
return a < b;
}

int main() {
std::vector<int> intVector = {3, 1, 4, 1, 5, 9, 2};
std::vector<std::string> stringVector = {"apple", "cherry", "banana"};

std::sort(intVector.begin(), intVector.end(), compareInt);
std::sort(stringVector.begin(), stringVector.end(), compareString);

return 0;
}

示例 2:函数指针作为参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int add(int a, int b) {
return a + b;
}

int multiply(int a, int b) {
return a * b;
}

int applyOperation(int a, int b, int (*operation)(int, int)) {
return operation(a, b);
}

int main() {
int result1 = applyOperation(5, 3, add);
int result2 = applyOperation(5, 3, multiply);

std::cout << "Result of addition: " << result1 << std::endl;
std::cout << "Result of multiplication: " << result2 << std::endl;

return 0;
}

示例 3:函数指针数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int operation1(int a) {
return a + 5;
}

int operation2(int a) {
return a * 2;
}

int operation3(int a) {
return a - 3;
}

int main() {
int (*functions[])(int) = {operation1, operation2, operation3};

for (int i = 0; i < 3; ++i) {
int result = functions[i](10);
std::cout << "Result of operation " << i + 1 << ": " << result << std::endl;
}

return 0;
}

示例 4:类成员函数作为函数指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Calculator {
public:
int add(int a, int b) {
return a + b;
}

int multiply(int a, int b) {
return a * b;
}
};

int main() {
Calculator calc;
int (Calculator::*operations[])(int, int) = {&Calculator::add, &Calculator::multiply};

for (auto& operation : operations) {
int result = (calc.*operation)(5, 3); // 使用成员函数指针调用成员函数
std::cout << "Result: " << result << std::endl;
}

return 0;
}
  • Title: C++
  • Author: Kaleido
  • Created at : 2024-04-26 14:15:20
  • Updated at : 2024-06-14 01:13:35
  • Link: https://redefine.ohevan.com/2024/04/26/C/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments