Second day of learning C++ in fourteen days (functions and libraries)

Insert image description here

1. Definition and calling of functions

In C++, functions are one of the key tools for organizing and structuring code. They allow you to encapsulate a piece of code into a reusable module, which helps make the code more readable and maintainable.

Why use functions?

The role of functions in programming cannot be underestimated. They have several important uses:

  • Modular programming: Functions allow code to be divided into small, independent units, making the code easier to understand and manage.

  • Code reuse: write once, use many times. You can call the same function in different places in your program without having to write the same code repeatedly.

  • Improve readability: By breaking your code into functions, you can give each function a descriptive name, making the code more readable.

define function

In C++, the definition of a function usually includes the following parts:

// 函数声明(函数原型)
返回类型 函数名(参数列表);

// 函数定义
返回类型 函数名(参数列表) {
    
    
    // 函数体
    // 执行一些操作
    return 返回值; // 如果有返回值的话
}
  • Return type: A function can return a value, the type of which is specified by the return type. If the function does not return any value, you can use voidthe keyword.

  • Function name: The name of the function, which is the identifier of the function.

  • Parameter list: A function can accept zero or more parameters, which are listed within parentheses and separated by commas.

  • Function body: Contains the actual code portion of the function execution.

  • Return value: If the function has a return value, use returnthe statement to return the value.

Function definition:

// 函数声明
int add(int a, int b);

// 函数定义
int add(int a, int b) {
    
    
    int result = a + b;
    return result;
}

Call functions

Calling a function means executing the code within the function. To call a function, simply use the function name and an appropriate argument list.

int main() {
    
    
    int num1 = 5;
    int num2 = 3;
    int sum = add(num1, num2); // 调用add函数
    cout << "Sum: " << sum << endl;
    return 0;
}

In the example, addthe function is called to calculate num1the sum num2of and and store the result in sumthe variable.

2. Parameter passing

In C++, parameter passing is one of the important ways for functions to exchange data with the external world. It can be implemented in different ways, including pass by value and pass by reference.

Pass by value vs. pass by reference

pass by value

When a parameter is passed to a function by value, the function creates a copy of the parameter, which means that changes to the parameter inside the function do not affect the original data outside.

void modifyValue(int x) {
    
    
    x = 10; // 在函数内部修改副本
}

int main() {
    
    
    int value = 5;
    modifyValue(value);
    cout << "Value after function call: " << value << endl; // 仍然是5
    return 0;
}
pass by reference

When parameters are passed by reference, the function operates on a reference to the original data, which means that changes to the parameters will affect the external original data.

void modifyValue(int &x) {
    
    
    x = 10; // 直接修改原始数据
}

int main() {
    
    
    int value = 5;
    modifyValue(value);
    cout << "Value after function call: " << value << endl; // 现在是10
    return 0;
}

Default values ​​for function parameters

Function parameters provide default values, which means that when calling a function, certain parameters can be omitted and the compiler uses default values.

void printMessage(string message = "Hello, World!") {
    
    
    cout << message << endl;
}

int main() {
    
    
    printMessage(); // 使用默认消息
    printMessage("Custom message"); // 使用自定义消息
    return 0;
}

function overloading

Function overloading allows multiple functions to be defined in the same scope with the same name but different parameter lists. The compiler chooses the correct function based on the parameters of the function call.

int add(int a, int b) {
    
    
    return a + b;
}

double add(double a, double b) {
    
    
    return a + b;
}

Example

Different ways of passing parameters and the impact of default values:

void modify(int x) {
    
    
    x = 10;
}

void modify(double &y) {
    
    
    y = 3.14;
}

int main() {
    
    
    int num = 5;
    double pi = 3.14159265359;

    modify(num); // 传值,num不变
    modify(pi);  // 传引用,pi被修改

    cout << "Modified num: " << num << endl;
    cout << "Modified pi: " << pi << endl;

    return 0;
}

In the example, modifythe function is passed parameters by value and by reference, resulting in different behaviors.

3. Return value of function

The return value of a function is the result provided to the caller after the function is executed. In C++, you can specify the return type of a function and use returnstatements to return values ​​from the function.

Return value type

Every C++ function has a return value type, which specifies the data type returned by the function. The return value type must be specified in both the function declaration and definition.

int add(int a, int b) {
    
     // 返回值类型为int
    return a + b;
}

double divide(double x, double y) {
    
     // 返回值类型为double
    return x / y;
}

return statement

returnStatement is used to return a value from a function. Can appear anywhere in a function, but once executed, the function terminates immediately and returns control to the caller.

int multiply(int a, int b) {
    
    
    int result = a * b;
    return result; // 返回计算结果
}

Example

Use the return value of the function:

int main() {
    
    
    int sum = add(5, 3); // 调用add函数并接收返回值
    double quotient = divide(10.0, 2.0); // 调用divide函数并接收返回值

    cout << "Sum: " << sum << endl;
    cout << "Quotient: " << quotient << endl;

    return 0;
}

In the above example, addthe and dividefunctions return integers and floating point numbers, which are stored in sumthe and quotientvariables respectively.

Use of return values ​​in expressions

The return value of a function can be used directly as part of an expression. This makes function calls very flexible and can be used in mathematical expressions or other calculations.

int main() {
    
    
    int result = multiply(add(2, 3), 4); // 使用函数返回值进行嵌套调用和计算

    cout << "Result: " << result << endl;

    return 0;
}

In the example, add(2, 3)the return value of is passed to multiplythe function for further calculations.

4. Introduction to the standard C++ library

As a powerful programming language, C++ has a rich standard library that provides many useful functions and data structures.

include header files

To use the functions in the C++ standard library, you first need to include the corresponding header file. Header files contain declarations of classes, functions, and objects in the library and are the key to using these libraries.

#include <iostream>  // 包含iostream头文件,用于输入输出操作
#include <string>    // 包含string头文件,用于字符串操作
#include <vector>    // 包含vector头文件,用于动态数组操作

Example usage

Example usage of the library:

Using iostream for input and output
#include <iostream>

int main() {
    
    
    // 输出文本到控制台
    std::cout << "Hello, World!" << std::endl;

    // 从用户输入读取数据
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    // 输出读取到的数据
    std::cout << "You entered: " << num << std::endl;

    return 0;
}
Using string for string operations
#include <string>

int main() {
    
    
    std::string greeting = "Hello, ";
    std::string name = "John";

    // 字符串拼接
    std::string message = greeting + name;

    // 获取字符串长度
    int length = message.length();

    // 输出结果
    std::cout << message << " (Length: " << length << ")" << std::endl;

    return 0;
}
Create dynamic array using vector
#include <vector>

int main() {
    
    
    std::vector<int> numbers;

    // 向vector添加元素
    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);

    // 遍历并输出vector的元素
    for (int i = 0; i < numbers.size(); ++i) {
    
    
        std::cout << numbers[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

5. Header files and namespaces

In C++ programming, header files and namespaces are very important concepts. Header files are used to contain declarations and definitions, and namespaces are used to avoid naming conflicts.

The role of header files

Header files usually contain declarations of functions, classes, and variables, as well as necessary function prototypes and constant definitions. The purpose of a header file is to group these declarations together so that they can be shared among multiple source files. This facilitates modular programming and improves code maintainability.

Create a custom header file

To create a custom header file, simply create a new text file with the .hor .hppextension and include the required declarations in it. For example, the following is myheader.han example of a header file named:

#ifndef MYHEADER_H
#define MYHEADER_H

// 在这里添加声明

#endif

The concept of namespace

Namespaces are a mechanism that divides the global scope into different parts to prevent naming conflicts. It allows you to organize related functions, classes, and variables into a namespace to avoid naming conflicts with other code.

Use namespaces

To use namespaces, you namespacedefine a namespace using keywords and then place relevant declarations inside it. For example:

// 定义一个名为mynamespace的命名空间
namespace mynamespace {
    
    
    int myVariable;
    void myFunction();
}
// 使用mynamespace中的变量和函数
mynamespace::myVariable = 42;
mynamespace::myFunction();

Simplify the use of namespaces

To simplify the use of namespaces, usingkeywords can be used to declare specific members in the namespace. For example:

// 使用mynamespace中的myVariable
using mynamespace::myVariable;

int main() {
    
    
    myVariable = 42; // 不需要指定命名空间
    return 0;
}

6.Case analysis

Function overloading :

#include <iostream>

// 函数重载:处理整数
int add(int a, int b) {
    
    
    return a + b;
}

// 函数重载:处理双精度浮点数
double add(double a, double b) {
    
    
    return a + b;
}

int main() {
    
    
    int intResult = add(5, 7);
    double doubleResult = add(3.5, 2.7);

    std::cout << "Integer Result: " << intResult << std::endl;
    std::cout << "Double Result: " << doubleResult << std::endl;

    return 0;
}

operation result:
Insert image description here

Recursive function :

#include <iostream>

int fibonacci(int n) {
    
    
    if (n <= 1) {
    
    
        return n;
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main() {
    
    
    int n = 10;
    for (int i = 0; i < n; ++i) {
    
    
        std::cout << fibonacci(i) << " ";
    }

    return 0;
}

operation result:
Insert image description here

Lambda expression :

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    
    
    std::vector<int> numbers = {
    
    5, 2, 8, 1, 3};

    // 使用Lambda表达式对向量进行排序
    std::sort(numbers.begin(), numbers.end(), [](int a, int b) {
    
    
        return a < b;
    });

    // 使用Lambda表达式筛选出偶数
    auto isEven = [](int x) {
    
     return x % 2 == 0; };
    std::vector<int> evenNumbers;

    std::copy_if(numbers.begin(), numbers.end(), std::back_inserter(evenNumbers), isEven);

    // 输出排序后的向量
    std::cout << "Sorted Numbers: ";
    for (int num : numbers) {
    
    
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 输出筛选后的偶数
    std::cout << "Even Numbers: ";
    for (int num : evenNumbers) {
    
    
        std::cout << num << " ";
    }
    std::cout << std::endl;

    return 0;
}

operation result:
Insert image description here

String processing :

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    
    
    std::string str = "Hello, World!";
    
    // 反转字符串
    std::reverse(str.begin(), str.end());
    std::cout << "Reversed String: " << str << std::endl;

    // 查找子字符串
    std::string subStr = "World";
    size_t found = str.find(subStr);
    if (found != std::string::npos) {
    
    
        std::cout << "Substring found at position: " << found << std::endl;
    } else {
    
    
        std::cout << "Substring not found." << std::endl;
    }

    // 将字符串拆分为单词
    std::string sentence = "This is a sample sentence";
    size_t startPos = 0;
    while (startPos < sentence.length()) {
    
    
        size_t spacePos = sentence.find(' ', startPos);
        if (spacePos == std::string::npos) {
    
    
            spacePos = sentence.length();
        }
        std::string word = sentence.substr(startPos, spacePos - startPos);
        std::cout << "Word: " << word << std::endl;
        startPos = spacePos + 1;
    }

    return 0;
}

operation result:
Insert image description here

Container operations :

#include <iostream>
#include <vector>
#include <algorithm>
#include <map>

int main() {
    
    
    // 使用std::vector进行容器操作
    std::vector<int> numbers = {
    
    5, 2, 8, 1, 3};

    // 添加元素
    numbers.push_back(7);

    // 删除元素
    numbers.erase(std::remove(numbers.begin(), numbers.end(), 3), numbers.end());

    // 对容器排序
    std::sort(numbers.begin(), numbers.end());

    // 输出容器元素
    std::cout << "Vector Elements: ";
    for (int num : numbers) {
    
    
        std::cout << num << " ";
    }
    std::cout << std::endl;

    // 使用std::map进行容器操作
    std::map<std::string, int> scores;

    // 添加键值对
    scores["Alice"] = 95;
    scores["Bob"] = 87;
    scores["Charlie"] = 92;

    // 查找元素
    std::string name = "Bob";
    if (scores.find(name) != scores.end()) {
    
    
        std::cout << name << "'s Score: " << scores[name] << std::endl;
    } else {
    
    
        std::cout << "Name not found." << std::endl;
    }

    return 0;
}

operation result:
Insert image description here

Multithreading and concurrency :

#include <iostream>
#include <thread>
#include <vector>

// 用于计算部分数组总和的函数
void partialSum(const std::vector<int>& arr, size_t start, size_t end, int& result) {
    
    
    result = 0;
    for (size_t i = start; i < end; ++i) {
    
    
        result += arr[i];
    }
}

int main() {
    
    
    const int numThreads = 4; // 使用4个线程
    const int arrSize = 1000;
    std::vector<int> numbers(arrSize, 1); // 创建一个包含1000个1的数组

    std::vector<std::thread> threads(numThreads);
    std::vector<int> partialResults(numThreads);

    // 创建并启动线程
    for (int i = 0; i < numThreads; ++i) {
    
    
        size_t start = i * (arrSize / numThreads);
        size_t end = (i == numThreads - 1) ? arrSize : (i + 1) * (arrSize / numThreads);
        threads[i] = std::thread(partialSum, std::ref(numbers), start, end, std::ref(partialResults[i]));
    }

    // 等待所有线程完成
    for (int i = 0; i < numThreads; ++i) {
    
    
        threads[i].join();
    }

    // 计算总和
    int totalSum = 0;
    for (int i = 0; i < numThreads; ++i) {
    
    
        totalSum += partialResults[i];
    }

    std::cout << "Total Sum: " << totalSum << std::endl;

    return 0;
}

operation result:
Insert image description here

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/133529207