iostream、fstream、sstream、string、vector、unordered_map、stack

iostream

用于输入输出操作,包含了处理标准输入输出流的功能(例如,cin, cout, cerr等)。

cpp 复制代码
#include <iostream>

int main() {
    int number;
    std::cout << "Enter a number: ";
    std::cin >> number;
    std::cout << "You entered: " << number << std::endl;
    return 0;
}

fstream

用于文件的读写操作。它提供了ifstream(用于读取文件),ofstream(用于写入文件),和fstream(可以同时用于读写文件)类。

cpp 复制代码
#include <fstream>
#include <iostream>

int main() {
    std::ofstream outfile("example.txt");
    outfile << "Hello, world!" << std::endl;
    outfile.close();
    
    std::ifstream infile("example.txt");
    std::string line;
    while (getline(infile, line)) {
        std::cout << line << std::endl;
    }
    infile.close();
    return 0;
}

sstream

用于字符串的流操作。主要提供了istringstream(从string读取数据),ostringstream(向string写入数据),和stringstream(可用于读写string)类。

cpp 复制代码
#include <sstream>
#include <iostream>

int main() {
    std::stringstream ss;
    ss << 100 << ' ' << 200;
    int foo, bar;
    ss >> foo >> bar;
    std::cout << foo << ", " << bar << std::endl;
    return 0;
}
cpp 复制代码
        while (getline(inputFile, line)) {
            stringstream ss(line);
            string token;
            vector<string> tokens;
            while (ss >> token) {
                tokens.push_back(token);
            }

string

提供了字符串处理功能,包括定义和操作std::string类型的对象。

cpp 复制代码
#include <string>
#include <iostream>

int main() {
    std::string str = "Hello, world!";
    std::cout << str << std::endl;
    return 0;
}

vector

实现了动态数组的功能,可以存储任意类型的对象,并且可以动态增长和缩小。

cpp 复制代码
#include <vector>
#include <iostream>

int main() {
    std::vector<int> vec = {1, 2, 3, 4, 5};
    for(int i : vec) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
    return 0;
}

unordered_map

提供了一种通过键来快速访问元素的方式,基于哈希表实现。它允许快速插入、删除和查找操作。

cpp 复制代码
#include <unordered_map>
#include <iostream>

int main() {
    std::unordered_map<std::string, int> map;
    map["one"] = 1;
    map["two"] = 2;
    std::cout << map["one"] << std::endl;
    return 0;
}

stack

实现了栈的数据结构,提供了后进先出(LIFO)的数据管理方式。

cpp 复制代码
#include <stack>
#include <iostream>

int main() {
    std::stack<int> stack;
    stack.push(1);
    stack.push(2);
    std::cout << stack.top() << std::endl;  // 查看栈顶元素
    stack.pop();                            // 移除栈顶元素
    std::cout << stack.top() << std::endl;
    return 0;
相关推荐
前端炒粉3 小时前
35.LRU 缓存
开发语言·javascript·数据结构·算法·缓存·js
断剑zou天涯5 小时前
【算法笔记】窗口内最大值或最小值的更新结构
java·笔记·算法
smj2302_796826525 小时前
解决leetcode第3753题范围内总波动值II
python·算法·leetcode
骑着猪去兜风.7 小时前
线段树(二)
数据结构·算法
fengfuyao9858 小时前
竞争性自适应重加权算法(CARS)的MATLAB实现
算法
散峰而望8 小时前
C++数组(二)(算法竞赛)
开发语言·c++·算法·github
leoufung8 小时前
LeetCode 92 反转链表 II 全流程详解
算法·leetcode·链表
wyhwust9 小时前
交换排序法&冒泡排序法& 选择排序法&插入排序的算法步骤
数据结构·算法·排序算法
利刃大大9 小时前
【动态规划:背包问题】完全平方数
c++·算法·动态规划·背包问题·完全背包
wyhwust9 小时前
数组----插入一个数到有序数列中
java·数据结构·算法