c++的标准库

介绍

C++的标准库是一组提供常用功能和数据结构的库,它是C++语言的一部分。标准库提供了许多预定义的类和函数,可以用于处理输入输出、字符串操作、数学计算、容器管理、算法实现等各种任务。主要有:

  • 输入输出库(iostream):提供了用于读取和写入数据的类和函数,包括cin、cout、cerr和clog等流对象。

  • 字符串库(string) : 提供了用于处理字符串的类和函数,例如字符串的连接、比较、查找、替换等操作。

  • 容器库(containers):包括各种容器类,如向量(vector)、链表(list)、队列(queue)、栈(stack)、集合(set)和映射(map)等,用于存储和组织数据。

  • 算法库(algorithms):提供了各种常用算法的实现,如排序、查找、合并、计数等,可以用于各种容器类型。

  • 数值库(numeric):提供了数值处理的功能,包括数学计算、随机数生成、数值比较和计算等。

  • 迭代器库(iterators):定义了一种通用的遍历容器元素的接口,使得可以使用相同的代码处理不同类型的容器。

  • 时间库(chrono):提供了时间处理的功能,包括时间点、时间间隔的表示和计算,以及定时器的功能。

  • 异常库(exception):提供了异常处理的机制,包括定义和抛出异常、捕获和处理异常等。

C++标准库还包括其他许多模块,如文件操作库、正则表达式库、多线程库、网络库等,提供了更丰富的功能和扩展性。

输入输出库iostream

  • istream和ostream类:它们是输入流和输出流的基类,分别用于处理输入和输出操作。

  • cin对象:是标准输入流对象,用于从键盘读取输入。

int num;
cin >> num; // 从键盘读取一个整数并存储到num变量中
  • cout对象:是标准输出流对象,用于向屏幕输出信息。
int num = 10;
cout << "The value of num is: " << num << endl; // 输出文本和变量的值
  • cerr对象:是标准错误流对象,用于输出错误信息。与cout不同,cerr的输出通常不会被重定向。
cerr << "Error: File not found!" << endl; // 输出错误信息
  • clog对象:是标准日志流对象,用于输出程序运行时的日志信息。
clog << "Processing data..." << endl; // 输出日志信息

字符串库string

  • string类:string类是C++中表示字符串的类,它提供了许多成员函数用于字符串的操作,如连接、比较、查找、替换等
#include <string>
using namespace std;

string str1 = "Hello";
string str2 = "World";

string result = str1 + " " + str2; // 字符串连接
cout << result << endl; // 输出:Hello World

if (str1 == "Hello") // 字符串比较
    cout << "str1 is equal to \"Hello\"" << endl;
  • length()和size()函数:这两个函数返回字符串的长度或大小。
string str = "Hello";
int len = str.length(); // 或者使用 str.size();
cout << "Length of the string is: " << len << endl; // 输出:Length of the string is: 5
  • substr()函数:该函数用于提取字符串的子串。
string str = "Hello World";
string sub = str.substr(6, 5); // 提取从索引6开始的长度为5的子串
cout << "Substring: " << sub << endl; // 输出:Substring: World
  • find()函数:该函数用于在字符串中查找指定的子串。
string str = "Hello World";
size_t pos = str.find("World"); // 查找子串的位置
if (pos != string::npos)
    cout << "Substring found at position: " << pos << endl; // 输出:Substring found at position: 6
  • replace()函数:用于替换字符串中的一部分内容。
string str = "Hello World";
str.replace(6, 5, "C++"); // 替换从索引6开始的长度为5的子串为"C++"
cout << "Modified string: " << str << endl; // 输出:Modified string: Hello C++

容器库containers

  • 向量(vector):向量是一种动态数组,可以在末尾高效地添加和删除元素。它提供了随机访问元素的能力。
#include <vector>
using namespace std;

vector<int> vec; // 声明一个整数向量

vec.push_back(1); // 添加元素到向量末尾
vec.push_back(2);
vec.push_back(3);

for (int i = 0; i < vec.size(); i++) {
    cout << vec[i] << " "; // 输出:1 2 3
}
  • 链表(list):链表是一种动态数据结构,可以高效地插入和删除元素。它不支持随机访问,只能通过迭代器进行遍历。
#include <list>
using namespace std;

list<int> myList; // 声明一个整数链表

myList.push_back(1); // 添加元素到链表末尾
myList.push_back(2);
myList.push_front(3); // 添加元素到链表头部

for (auto it = myList.begin(); it != myList.end(); ++it) {
    cout << *it << " "; // 输出:3 1 2
}
  • 队列(queue):队列是一种先进先出(FIFO)的数据结构,可以在末尾添加元素,在头部删除元素。
#include <queue>
using namespace std;

queue<int> myQueue; // 声明一个整数队列

myQueue.push(1); // 添加元素到队列末尾
myQueue.push(2);
myQueue.push(3);

while (!myQueue.empty()) {
    cout << myQueue.front() << " "; // 输出:1 2 3
    myQueue.pop(); // 删除队列头部元素
}
  • 栈(stack):栈是一种后进先出(LIFO)的数据结构,可以在顶部添加元素和删除元素。
#include <stack>
using namespace std;

stack<int> myStack; // 声明一个整数栈

myStack.push(1); // 添加元素到栈顶
myStack.push(2);
myStack.push(3);

while (!myStack.empty()) {
    cout << myStack.top() << " "; // 输出:3 2 1
    myStack.pop(); // 删除栈顶元素
}
  • 集合(set)和映射(map):集合是一种不重复元素的容器,映射是一种键—值对的容器。
#include <set>
#include <map>
using namespace std;

set<int> mySet; // 声明一个整数集合

mySet.insert(1); // 添加元素到集合
mySet.insert(2);
mySet.insert(3);

for (const auto& element : mySet) {
    cout << element << " "; // 输出:1 2 3
}

map<string, int> myMap; // 声明一个字符串到整数的映射

myMap["one"] = 1; // 添加键值对到映射
myMap["two"] = 2;
myMap["three"] = 3;

for (const auto& pair : myMap) {
    cout << pair.first << ": " << pair.second << endl; // 输出:one: 1, two: 2, three: 3
}

数值库numeric

  • 数值处理(Numeric Processing):数值库提供了一些函数和算法,用于执行数值处理操作,如绝对值、取余、幂运算、平方根等。
#include <cmath>
using namespace std;

double num = -2.5;
double absValue = abs(num); // 绝对值
double squareRoot = sqrt(num); // 平方根

cout << "Absolute value: " << absValue << endl; // 输出:Absolute value: 2.5
cout << "Square root: " << squareRoot << endl; // 输出:Square root: nan
  • 随机数生成(Random Number Generation):数值库提供了生成随机数的函数和类,用于产生伪随机数序列。-
#include <random>
using namespace std;

random_device rd; // 随机数种子
default_random_engine generator(rd()); // 随机数生成器

uniform_int_distribution<int> distribution(1, 6); // 生成1到6之间的均匀分布的整数

int randomNumber = distribution(generator); // 生成随机数

cout << "Random number: " << randomNumber << endl; // 输出:Random number: [1-6]
  • 数学函数(Mathematical Functions):数值库提供了一些常用的数学函数,如三角函数、对数函数、指数函数等。
#include <cmath>
using namespace std;

double angle = 45.0;
double radians = angle * M_PI / 180.0;
double sinValue = sin(radians); // 正弦函数

cout << "Sin value: " << sinValue << endl; // 输出:Sin value: 0.707107
  • 复数处理(Complex Number Handling):数值库提供了用于处理复数的类和函数,支持复数的运算和操作。
#include <complex>
using namespace std;

complex<double> z1(2.0, 3.0); // 复数 z1 = 2 + 3i
complex<double> z2(4.0, -1.0); // 复数 z2 = 4 - i

complex<double> sum = z1 + z2; // 复数相加

cout << "Sum: " << sum.real() << " + " << sum.imag() << "i" << endl; // 输出:Sum: 6 + 2i

迭代器库iterators

C++的迭代器库(iterator)是C++标准库中的一部分,提供了一种统一的访问容器元素的方式。迭代器(iterator)是一种类似指针的对象,用于遍历和访问容器中的元素,而不需要了解容器的内部实现细节。

  • 迭代器类型(Iterator Types):迭代器库定义了不同类型的迭代器,用于访问不同类型的容器。常见的迭代器类型有:
类型解释
输入迭代器(Input Iterator)用于从容器中读取元素,支持单向顺序访问。
输出迭代器(Output Iterator)用于向容器中写入元素,支持单向顺序访问。
前向迭代器(Forward Iterator)支持单向顺序遍历容器,可读写元素。
双向迭代器(Bidirectional Iterator)支持双向遍历容器,可读写元素。
随机访问迭代器(Random Access Iterator)支持随机访问容器,具有指针类似的功能,可读写元素。
  • 迭代器操作(Iterator Operations):迭代器库提供了一系列操作函数和方法,用于对迭代器进行操作,如移动迭代器位置、访问元素、比较迭代器等。
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};

    // 使用迭代器遍历容器
    vector<int>::iterator it;
    for (it = vec.begin(); it != vec.end(); ++it) {
        cout << *it << " "; // 输出:1 2 3 4 5
    }

    cout << endl;

    // 使用迭代器修改容器元素
    for (it = vec.begin(); it != vec.end(); ++it) {
        *it *= 2;
    }

    // 使用迭代器输出修改后的容器
    for (it = vec.begin(); it != vec.end(); ++it) {
        cout << *it << " "; // 输出:2 4 6 8 10
    }

    return 0;
}
  • 迭代器适配器(Iterator Adapters):迭代器库还提供了一些适配器,用于对迭代器进行功能扩展和转换。常见的迭代器适配器有反向迭代器(reverse_iterator)和插入迭代器(insert_iterator)等。
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;

int main() {
    vector<int> vec = {1, 2, 3, 4, 5};

    // 使用反向迭代器逆序遍历容器
    vector<int>::reverse_iterator rit;
    for (rit = vec.rbegin(); rit != vec.rend(); ++rit) {
        cout << *rit << " "; // 输出:5 4 3 2 1
    }

    cout << endl;

    // 使用插入迭代器将元素插入容器
    vector<int> newVec;
    back_insert_iterator<vector<int>> backIt(newVec);

    for (int i = 0; i < 5; ++i) {
        *backIt = i; // 插入元素到容器尾部
        ++backIt;
    }

    // 输出插入后的容器
    copy(newVec.begin(), newVec.end(), ostream_iterator<int>(cout, " ")); // 输出:0 1 2 3 4

    return 0;
}

时间库chrono

  • 时间点(Time Point):时间点表示具体的时间,可以是相对于某个基准时间的绝对时间或相对时间。时间点可以精确到纳秒级别。
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;

int main() {
    // 获取当前时间点
    system_clock::time_point now = system_clock::now();

    // 将时间点转换为时间戳(秒数)
    time_t timestamp = system_clock::to_time_t(now);

    // 输出当前时间戳
    cout << "Timestamp: " << timestamp << endl;

    return 0;
}
  • 时间间隔(Time Duration):时间间隔表示两个时间点之间的时间差,可以表示秒、毫秒、微秒、纳秒等精度的时间跨度。
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;

int main() {
    // 计算程序执行时间
    steady_clock::time_point start = steady_clock::now();

    // 执行一些操作...

    steady_clock::time_point end = steady_clock::now();
    duration<double> duration = duration_cast<duration<double>>(end - start);

    // 输出程序执行时间
    cout << "Execution time: " << duration.count() << " seconds" << endl;

    return 0;
}
  • 时钟(Clock):时钟提供了不同的时间基准,用于获取时间点和测量时间间隔。常见的时钟包括系统时钟(system_clock)、高精度时钟(high_resolution_clock)和稳定时钟(steady_clock)。
#include <iostream>
#include <chrono>
using namespace std;
using namespace std::chrono;

int main() {
    // 获取当前系统时间
    system_clock::time_point sysTime = system_clock::now();

    // 获取高精度时间
    high_resolution_clock::time_point highResTime = high_resolution_clock::now();

    // 获取稳定时间
    steady_clock::time_point steadyTime = steady_clock::now();

    return 0;
}
  • 日期和时间转换(Date and Time Conversion):时间库提供了一些函数和方法,用于日期和时间的转换和格式化。
#include <iostream>
#include <chrono>
#include <ctime>
using namespace std;
using namespace std::chrono;

int main() {
    // 获取当前时间点
    system_clock::time_point now = system_clock::now();

    // 将时间点转换为C风格字符串
    time_t currentTime = system_clock::to_time_t(now);
    char* timeStr = ctime(&currentTime);

    // 输出当前时间
    cout << "Current time: " << timeStr;

    return 0;
}

异常库exception。

  • 异常类(Exception Classes):异常库定义了一些异常类,用于表示不同类型的异常情况。通常,这些异常类是从标准异常类(std::exception)派生而来的,可以根据具体的异常情况定义自己的异常类。
#include <iostream>
#include <exception>
using namespace std;

class MyException : public exception {
public:
    const char* what() const throw() {
        return "My Exception";
    }
};

int main() {
    try {
        throw MyException();
    } catch (exception& e) {
        cout << "Caught Exception: " << e.what() << endl;
    }

    return 0;
}
  • 异常处理(Exception Handling):使用异常处理机制,可以在程序中捕获和处理异常。通过try-catch块,可以捕获特定类型的异常,并采取相应的处理措施,如输出错误信息、进行恢复操作或抛出新的异常。
#include <iostream>
using namespace std;

int main() {
    try {
        int numerator = 10;
        int denominator = 0;
        if (denominator == 0) {
            throw runtime_error("Division by zero");
        }
        int result = numerator / denominator;
        cout << "Result: " << result << endl;
    } catch (exception& e) {
        cout << "Exception caught: " << e.what() << endl;
    }

    return 0;
}
  • 异常传播(Exception Propagation):异常处理机制允许异常在函数调用栈中传播。如果在函数内部发生异常但未被捕获处理,该异常会被传递给调用者,直到找到合适的异常处理代码或程序终止。
#include <iostream>
using namespace std;

void functionB() {
    throw runtime_error("Exception in functionB");
}

void functionA() {
    try {
        functionB();
    } catch (exception& e) {
        cout << "Exception caught in functionA: " << e.what() << endl;
        throw; // 重新抛出异常
    }
}

int main() {
    try {
        functionA();
    } catch (exception& e) {
        cout << "Exception caught in main: " << e.what() << endl;
    }

    return 0;
}
  • 异常规范(Exception Specification):异常规范用于声明函数可能抛出的异常类型。在函数声明中使用throw()或noexcept关键字可以指定函数不会抛出异常,或者使用throw(Type1, Type2, …)的形式指定函数可能抛出的异常类型列表。
#include <iostream>
using namespace std;

void functionA() throw(runtime_error) {
    throw runtime_error("Exception in functionA");
}

int main() {
    try {
        functionA();
    } catch (exception& e) {
        cout << "Exception caught: " << e.what() << endl;
    }

    return 0;
}
  • 7
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Codec Conductor

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值