C++上机代码实例51-100
·
51. 学生类(基础类设计)
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int id;
double score;
public:
Student(string n, int i, double s) : name(n), id(i), score(s) {}
void display() const {
cout << "姓名: " << name << "\n学号: " << id
<< "\n成绩: " << score << endl;
}
void setScore(double s) { score = s; }
};
int main() {
Student stu("张三", 2023001, 89.5);
stu.display();
stu.setScore(92.0);
cout << "修改后成绩: ";
stu.display();
return 0;
}
52. 复数类(运算符重载)
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// 重载+运算符
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
// 重载输出运算符
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << (c.imag >= 0 ? "+" : "") << c.imag << "i";
return os;
}
};
int main() {
Complex c1(3, 4), c2(1, -2);
Complex sum = c1 + c2;
cout << c1 << " + " << c2 << " = " << sum << endl;
return 0;
}
53. 静态成员统计对象数
#include <iostream>
using namespace std;
class Counter {
private:
static int count; // 静态成员声明
public:
Counter() { count++; }
~Counter() { count--; }
static int getCount() { return count; }
};
int Counter::count = 0; // 静态成员定义
int main() {
Counter c1, c2;
cout << "当前对象数: " << Counter::getCount() << endl;
{
Counter c3;
cout << "进入作用域后: " << Counter::getCount() << endl;
}
cout << "离开作用域后: " << Counter::getCount() << endl;
return 0;
}
54. 单例模式实现
#include <iostream>
using namespace std;
class Singleton {
private:
static Singleton* instance;
string data;
// 私有构造函数
Singleton(string d) : data(d) {}
public:
// 删除拷贝构造和赋值
Singleton(const Singleton&) = delete;
void operator=(const Singleton&) = delete;
static Singleton* getInstance(string d) {
if (!instance) {
instance = new Singleton(d);
}
return instance;
}
void showData() const {
cout << "单例数据: " << data << endl;
}
};
Singleton* Singleton::instance = nullptr;
int main() {
Singleton* s1 = Singleton::getInstance("初始化数据");
s1->showData();
// 尝试创建新实例
Singleton* s2 = Singleton::getInstance("新数据");
s2->showData(); // 仍然输出原始数据
return 0;
}
55. 异常处理示例
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw runtime_error("除数不能为零!");
}
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(5, 0) << endl; // 触发异常
} catch (const exception& e) {
cerr << "错误: " << e.what() << endl;
}
return 0;
}
56. vector容器基本操作
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {5, 2, 8, 1, 9};
// 遍历1:索引遍历
cout << "原始数据: ";
for (size_t i = 0; i < vec.size(); ++i) {
cout << vec[i] << " ";
}
// 排序
sort(vec.begin(), vec.end());
// 遍历2:迭代器
cout << "\n排序后: ";
for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}
// 遍历3:范围for
cout << "\n使用范围for: ";
for (int num : vec) {
cout << num << " ";
}
return 0;
}
57. map容器统计词频
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<string, int> wordCount;
string word;
cout << "输入单词(end结束):\n";
while (cin >> word && word != "end") {
wordCount[word]++;
}
cout << "\n词频统计:\n";
for (const auto& pair : wordCount) {
cout << pair.first << ": " << pair.second << "次\n";
}
return 0;
}
58. stack实现括号匹配
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isBalanced(const string& expr) {
stack<char> s;
for (char c : expr) {
if (c == '(' || c == '[' || c == '{') {
s.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (s.empty()) return false;
char top = s.top();
s.pop();
if ((c == ')' && top != '(') ||
(c == ']' && top != '[') ||
(c == '}' && top != '{')) {
return false;
}
}
}
return s.empty();
}
int main() {
string expr = "{([a+b]*[c-d])/e}";
cout << expr << (isBalanced(expr) ? " 括号匹配" : " 括号不匹配") << endl;
return 0;
}
59. queue模拟排队系统
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
queue<string> waitingLine;
// 入队
waitingLine.push("顾客1");
waitingLine.push("顾客2");
waitingLine.push("顾客3");
// 服务过程
while (!waitingLine.empty()) {
cout << "正在服务: " << waitingLine.front() << endl;
waitingLine.pop();
cout << "剩余排队人数: " << waitingLine.size() << endl;
}
return 0;
}
60. priority_queue优先级调度
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int main() {
// 大顶堆(默认)
priority_queue<int> maxHeap;
// 小顶堆
priority_queue<int, vector<int>, greater<int>> minHeap;
// 添加元素
for (int num : {3, 1, 4, 1, 5}) {
maxHeap.push(num);
minHeap.push(num);
}
cout << "大顶堆出队: ";
while (!maxHeap.empty()) {
cout << maxHeap.top() << " ";
maxHeap.pop();
}
cout << "\n小顶堆出队: ";
while (!minHeap.empty()) {
cout << minHeap.top() << " ";
minHeap.pop();
}
return 0;
}
61. 形状类继承体系
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() const = 0; // 纯虚函数
virtual void print() const {
cout << "图形面积: " << area() << endl;
}
virtual ~Shape() {} // 虚析构函数
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return 3.14159 * radius * radius;
}
void print() const override {
cout << "圆形 半径=" << radius << ", ";
Shape::print();
}
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
void print() const override {
cout << "矩形 " << width << "x" << height << ", ";
Shape::print();
}
};
int main() {
Shape* shapes[] = {new Circle(5), new Rectangle(4, 6)};
for (Shape* s : shapes) {
s->print();
delete s; // 多态删除
}
return 0;
}
62. 虚函数与多态
#include <iostream>
using namespace std;
class Animal {
public:
virtual void speak() const {
cout << "动物发出声音" << endl;
}
};
class Dog : public Animal {
public:
void speak() const override {
cout << "汪汪!" << endl;
}
};
class Cat : public Animal {
public:
void speak() const override {
cout << "喵喵!" << endl;
}
};
void animalSound(const Animal& animal) {
animal.speak(); // 多态调用
}
int main() {
Dog dog;
Cat cat;
animalSound(dog);
animalSound(cat);
return 0;
}
63. 抽象类与接口
#include <iostream>
using namespace std;
// 抽象类
class Printable {
public:
virtual void print() const = 0;
virtual ~Printable() = default;
};
// 接口类
class Drawable {
public:
virtual void draw() const = 0;
virtual ~Drawable() = default;
};
class Circle : public Printable, public Drawable {
double radius;
public:
Circle(double r) : radius(r) {}
void print() const override {
cout << "圆形 半径=" << radius << endl;
}
void draw() const override {
cout << "绘制圆形..." << endl;
}
};
int main() {
Circle c(5);
Printable* p = &c;
Drawable* d = &c;
p->print();
d->draw();
return 0;
}
64. 动态类型转换
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base {
public:
void specificMethod() {
cout << "Derived类特有方法" << endl;
}
};
int main() {
Base* b = new Derived;
// dynamic_cast检查
if (Derived* d = dynamic_cast<Derived*>(b)) {
d->specificMethod();
} else {
cout << "转换失败" << endl;
}
// typeid获取类型信息
cout << "实际类型: " << typeid(*b).name() << endl;
delete b;
return 0;
}
65. 多重继承
#include <iostream>
using namespace std;
class A {
public:
void showA() { cout << "A类方法" << endl; }
};
class B {
public:
void showB() { cout << "B类方法" << endl; }
};
class C : public A, public B {
public:
void showC() {
showA();
showB();
cout << "C类方法" << endl;
}
};
int main() {
C c;
c.showC();
return 0;
}
66. 类模板
#include <iostream>
using namespace std;
template <typename T>
class Box {
T content;
public:
Box(T c) : content(c) {}
void show() const {
cout << "盒子内容: " << content << endl;
}
};
int main() {
Box<int> intBox(42);
Box<string> strBox("Hello Templates");
intBox.show();
strBox.show();
return 0;
}
67. 函数模板特化
#include <iostream>
#include <cstring>
using namespace std;
// 通用模板
template <typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
// 特化版本(C风格字符串)
template <>
const char* maxValue(const char* a, const char* b) {
return (strcmp(a, b) > 0) ? a : b;
}
int main() {
cout << maxValue(3, 7) << endl;
cout << maxValue("apple", "orange") << endl;
return 0;
}
68. 智能指针
#include <iostream>
#include <memory>
using namespace std;
class Resource {
public:
Resource() { cout << "资源获取" << endl; }
~Resource() { cout << "资源释放" << endl; }
void use() { cout << "使用资源..." << endl; }
};
int main() {
// unique_ptr(独占所有权)
unique_ptr<Resource> up1(new Resource);
up1->use();
// shared_ptr(共享所有权)
shared_ptr<Resource> sp1(new Resource);
{
auto sp2 = sp1; // 引用计数+1
sp2->use();
} // sp2析构,引用计数-1
// weak_ptr(观察但不拥有)
weak_ptr<Resource> wp = sp1;
if (auto temp = wp.lock()) {
temp->use();
}
return 0;
}
69. 移动语义
#include <iostream>
#include <vector>
using namespace std;
class StringWrapper {
char* data;
public:
// 构造函数
explicit StringWrapper(const char* str = "") {
data = new char[strlen(str) + 1];
strcpy(data, str);
cout << "构造: " << data << endl;
}
// 移动构造函数
StringWrapper(StringWrapper&& other) noexcept
: data(other.data) {
other.data = nullptr;
cout << "移动构造" << endl;
}
// 移动赋值运算符
StringWrapper& operator=(StringWrapper&& other) noexcept {
if (this != &other) {
delete[] data;
data = other.data;
other.data = nullptr;
cout << "移动赋值" << endl;
}
return *this;
}
~StringWrapper() {
if (data) {
cout << "析构: " << data << endl;
delete[] data;
}
}
};
int main() {
vector<StringWrapper> vec;
vec.push_back(StringWrapper("Hello")); // 触发移动构造
StringWrapper a("World");
StringWrapper b = move(a); // 显式移动
return 0;
}
70. Lambda表达式捕获
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
int threshold = 3;
// 值捕获
auto count1 = {
return threshold; // 捕获时的threshold值
};
// 引用捕获
auto count2 = {
return ++threshold; // 修改外部变量
};
// 混合捕获
auto printNums = {
cout << "阈值=" << threshold << ": ";
for (int n : nums) cout << n << " ";
cout << endl;
};
cout << count1() << endl; // 输出3
cout << count2() << endl; // 输出4(修改了threshold)
printNums();
// 在算法中使用lambda
auto it = find_if(nums.begin(), nums.end(),
int n { return n > threshold; });
if (it != nums.end()) {
cout << "第一个大于" << threshold << "的数: " << *it << endl;
}
return 0;
}
71. 文件读写(文本模式)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void writeToFile(const string& filename) {
ofstream outFile(filename);
if (!outFile) {
cerr << "文件打开失败" << endl;
return;
}
outFile << "第一行文本\n第二行文本\n第三行文本";
cout << "数据已写入文件" << endl;
}
void readFromFile(const string& filename) {
ifstream inFile(filename);
if (!inFile) {
cerr << "文件打开失败" << endl;
return;
}
string line;
cout << "文件内容:\n";
while (getline(inFile, line)) {
cout << line << endl;
}
}
int main() {
const string filename = "example.txt";
writeToFile(filename);
readFromFile(filename);
return 0;
}
72. 二进制文件操作
#include <iostream>
#include <fstream>
using namespace std;
struct Person {
char name[50];
int age;
double height;
};
void writeBinary(const string& filename) {
ofstream outFile(filename, ios::binary);
if (!outFile) {
cerr << "文件打开失败" << endl;
return;
}
Person p1 = {"张三", 25, 175.5};
Person p2 = {"李四", 30, 168.0};
outFile.write(reinterpret_cast<char*>(&p1), sizeof(Person));
outFile.write(reinterpret_cast<char*>(&p2), sizeof(Person));
cout << "二进制数据已写入" << endl;
}
void readBinary(const string& filename) {
ifstream inFile(filename, ios::binary);
if (!inFile) {
cerr << "文件打开失败" << endl;
return;
}
Person p;
cout << "读取二进制数据:\n";
while (inFile.read(reinterpret_cast<char*>(&p), sizeof(Person))) {
cout << "姓名: " << p.name << ", 年龄: " << p.age
<< ", 身高: " << p.height << endl;
}
}
int main() {
const string filename = "data.bin";
writeBinary(filename);
readBinary(filename);
return 0;
}
73. 自定义异常类
#include <iostream>
#include <stdexcept>
using namespace std;
class NegativeValueException : public runtime_error {
public:
NegativeValueException(const string& msg)
: runtime_error(msg) {}
};
double calculateSqrt(double x) {
if (x < 0) {
throw NegativeValueException("负数不能开平方");
}
return sqrt(x);
}
int main() {
try {
cout << calculateSqrt(9) << endl;
cout << calculateSqrt(-4) << endl;
} catch (const NegativeValueException& e) {
cerr << "错误捕获: " << e.what() << endl;
}
return 0;
}
74. 工厂模式
#include <iostream>
#include <memory>
using namespace std;
// 抽象产品
class Shape {
public:
virtual void draw() const = 0;
virtual ~Shape() = default;
};
// 具体产品
class Circle : public Shape {
public:
void draw() const override {
cout << "绘制圆形" << endl;
}
};
class Rectangle : public Shape {
public:
void draw() const override {
cout << "绘制矩形" << endl;
}
};
// 工厂类
class ShapeFactory {
public:
enum ShapeType { CIRCLE, RECTANGLE };
static unique_ptr<Shape> createShape(ShapeType type) {
switch (type) {
case CIRCLE: return make_unique<Circle>();
case RECTANGLE: return make_unique<Rectangle>();
default: throw invalid_argument("无效类型");
}
}
};
int main() {
auto circle = ShapeFactory::createShape(ShapeFactory::CIRCLE);
auto rect = ShapeFactory::createShape(ShapeFactory::RECTANGLE);
circle->draw();
rect->draw();
return 0;
}
75. 观察者模式
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 观察者接口
class Observer {
public:
virtual void update(const string& message) = 0;
virtual ~Observer() = default;
};
// 具体观察者
class ConcreteObserver : public Observer {
string name;
public:
ConcreteObserver(string n) : name(n) {}
void update(const string& message) override {
cout << name << " 收到消息: " << message << endl;
}
};
// 主题
class Subject {
vector<Observer*> observers;
public:
void attach(Observer* obs) {
observers.push_back(obs);
}
void detach(Observer* obs) {
observers.erase(remove(observers.begin(), observers.end(), obs),
observers.end());
}
void notify(const string& message) {
for (auto obs : observers) {
obs->update(message);
}
}
};
int main() {
Subject subject;
ConcreteObserver obs1("观察者1"), obs2("观察者2");
subject.attach(&obs1);
subject.attach(&obs2);
subject.notify("第一次通知");
subject.detach(&obs1);
subject.notify("第二次通知");
return 0;
}
76. 命令模式
#include <iostream>
#include <vector>
using namespace std;
// 命令接口
class Command {
public:
virtual void execute() = 0;
virtual ~Command() = default;
};
// 具体命令
class LightOnCommand : public Command {
public:
void execute() override {
cout << "电灯已打开" << endl;
}
};
class LightOffCommand : public Command {
public:
void execute() override {
cout << "电灯已关闭" << endl;
}
};
// 调用者
class RemoteControl {
vector<Command*> commands;
public:
void addCommand(Command* cmd) {
commands.push_back(cmd);
}
void pressButton(int index) {
if (index >= 0 && index < commands.size()) {
commands[index]->execute();
}
}
};
int main() {
RemoteControl remote;
LightOnCommand onCmd;
LightOffCommand offCmd;
remote.addCommand(&onCmd);
remote.addCommand(&offCmd);
remote.pressButton(0); // 开灯
remote.pressButton(1); // 关灯
return 0;
}
77. 策略模式
#include <iostream>
using namespace std;
// 策略接口
class SortingStrategy {
public:
virtual void sort(int arr[], int size) = 0;
virtual ~SortingStrategy() = default;
};
// 具体策略
class BubbleSort : public SortingStrategy {
public:
void sort(int arr[], int size) override {
cout << "使用冒泡排序" << endl;
for (int i = 0; i < size-1; i++) {
for (int j = 0; j < size-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
};
class QuickSort : public SortingStrategy {
public:
void sort(int arr[], int size) override {
cout << "使用快速排序" << endl;
quickSort(arr, 0, size-1);
}
private:
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi+1, high);
}
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[high]);
return i+1;
}
};
// 上下文
class Sorter {
SortingStrategy* strategy;
public:
Sorter(SortingStrategy* s) : strategy(s) {}
void setStrategy(SortingStrategy* s) {
strategy = s;
}
void performSort(int arr[], int size) {
strategy->sort(arr, size);
}
};
int main() {
int arr[] = {5, 2, 9, 1, 5};
int size = sizeof(arr)/sizeof(arr[0]);
BubbleSort bubble;
QuickSort quick;
Sorter sorter(&bubble);
sorter.performSort(arr, size);
cout << "排序后数组: ";
for (int i = 0; i < size; i++) cout << arr[i] << " ";
cout << endl;
sorter.setStrategy(&quick);
sorter.performSort(arr, size);
return 0;
}
78. 适配器模式
#include <iostream>
using namespace std;
// 不兼容的接口
class LegacyRectangle {
int x1, y1, x2, y2;
public:
LegacyRectangle(int x1, int y1, int x2, int y2)
: x1(x1), y1(y1), x2(x2), y2(y2) {}
void oldDraw() {
cout << "旧式绘制: (" << x1 << "," << y1 << ") to ("
<< x2 << "," << y2 << ")" << endl;
}
};
// 目标接口
class Rectangle {
public:
virtual void draw() = 0;
virtual ~Rectangle() = default;
};
// 适配器
class RectangleAdapter : public Rectangle {
LegacyRectangle* legacyRect;
public:
RectangleAdapter(int x, int y, int w, int h) {
legacyRect = new LegacyRectangle(x, y, x+w, y+h);
}
void draw() override {
legacyRect->oldDraw();
}
~RectangleAdapter() {
delete legacyRect;
}
};
int main() {
Rectangle* rect = new RectangleAdapter(10, 20, 30, 40);
rect->draw();
delete rect;
return 0;
}
79. 装饰器模式
#include <iostream>
#include <string>
using namespace std;
// 组件接口
class Beverage {
public:
virtual string getDescription() = 0;
virtual double cost() = 0;
virtual ~Beverage() = default;
};
// 具体组件
class Coffee : public Beverage {
public:
string getDescription() override {
return "咖啡";
}
double cost() override {
return 2.0;
}
};
// 装饰器基类
class CondimentDecorator : public Beverage {
protected:
Beverage* beverage;
public:
CondimentDecorator(Beverage* b) : beverage(b) {}
virtual ~CondimentDecorator() {
delete beverage;
}
};
// 具体装饰器
class Milk : public CondimentDecorator {
public:
Milk(Beverage* b) : CondimentDecorator(b) {}
string getDescription() override {
return beverage->getDescription() + ", 牛奶";
}
double cost() override {
return beverage->cost() + 0.5;
}
};
class Sugar : public CondimentDecorator {
public:
Sugar(Beverage* b) : CondimentDecorator(b) {}
string getDescription() override {
return beverage->getDescription() + ", 糖";
}
double cost() override {
return beverage->cost() + 0.2;
}
};
int main() {
Beverage* drink = new Coffee();
cout << drink->getDescription() << " 价格: $" << drink->cost() << endl;
drink = new Milk(drink);
drink = new Sugar(drink);
cout << drink->getDescription() << " 价格: $" << drink->cost() << endl;
delete drink;
return 0;
}
80. 状态模式
#include <iostream>
using namespace std;
// 状态接口
class State {
public:
virtual void handle() = 0;
virtual ~State() = default;
};
// 具体状态
class ConcreteStateA : public State {
public:
void handle() override {
cout << "处理状态A的行为" << endl;
}
};
class ConcreteStateB : public State {
public:
void handle() override {
cout << "处理状态B的行为" << endl;
}
};
// 上下文
class Context {
State* state;
public:
Context(State* s) : state(s) {}
void setState(State* s) {
state = s;
}
void request() {
state->handle();
}
};
int main() {
ConcreteStateA stateA;
ConcreteStateB stateB;
Context context(&stateA);
context.request();
context.setState(&stateB);
context.request();
return 0;
}
81. 指针操作数组
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr; // 指向数组首元素
cout << "通过指针访问数组:" << endl;
for (int i = 0; i < 5; i++) {
cout << "元素" << i << ": " << *(ptr + i) << endl;
// 等价于 ptr[i] 或 arr[i]
}
// 指针算术运算
ptr += 3; // 移动指针到第4个元素
cout << "指针偏移后: " << *ptr << endl;
return 0;
}
82. 动态数组
#include <iostream>
using namespace std;
int main() {
int size;
cout << "输入数组大小: ";
cin >> size;
// 动态分配数组
int* dynamicArray = new int[size];
// 初始化数组
for (int i = 0; i < size; i++) {
dynamicArray[i] = i * 10;
}
// 打印数组
cout << "动态数组内容: ";
for (int i = 0; i < size; i++) {
cout << dynamicArray[i] << " ";
}
// 释放内存
delete[] dynamicArray;
return 0;
}
83. 指针与函数
#include <iostream>
using namespace std;
// 通过指针修改实参
void increment(int* ptr) {
(*ptr)++; // 解引用后自增
}
// 返回动态分配数组的指针
int* createArray(int size) {
int* arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
int main() {
int num = 5;
increment(&num);
cout << "增量后: " << num << endl;
int* myArray = createArray(5);
cout << "动态数组: ";
for (int i = 0; i < 5; i++) {
cout << myArray[i] << " ";
}
delete[] myArray; // 必须手动释放
return 0;
}
84. 指针数组
#include <iostream>
using namespace std;
int main() {
const char* names[] = {"Alice", "Bob", "Charlie"}; // 指针数组
cout << "名字列表:" << endl;
for (int i = 0; i < 3; i++) {
cout << i << ": " << names[i] << endl;
}
// 修改指针指向
const char* newName = "David";
names[1] = newName;
cout << "修改后: " << names[1] << endl;
return 0;
}
85. 函数指针数组
#include <iostream>
using namespace std;
// 定义函数类型
typedef void (*Operation)(int, int);
void add(int a, int b) { cout << a + b << endl; }
void subtract(int a, int b) { cout << a - b << endl; }
void multiply(int a, int b) { cout << a * b << endl; }
int main() {
// 函数指针数组
Operation operations[] = {add, subtract, multiply};
cout << "选择操作 (0-加 1-减 2-乘): ";
int choice;
cin >> choice;
if (choice >= 0 && choice <= 2) {
cout << "输入两个数: ";
int x, y;
cin >> x >> y;
operationsx, y; // 通过指针调用函数
} else {
cout << "无效选择" << endl;
}
return 0;
}
86. 动态二维数组
#include <iostream>
using namespace std;
int main() {
int rows, cols;
cout << "输入行数和列数: ";
cin >> rows >> cols;
// 分配行指针数组
int** matrix = new int*[rows];
// 为每行分配列数组
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// 初始化矩阵
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = i * 10 + j;
}
}
// 打印矩阵
cout << "动态二维数组:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << matrix[i][j] << "\t";
}
cout << endl;
}
// 释放内存
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
return 0;
}
87. 引用 vs 指针
#include <iostream>
using namespace std;
void swapByPointer(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void swapByReference(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
cout << "原始值: x=" << x << ", y=" << y << endl;
swapByPointer(&x, &y);
cout << "指针交换后: x=" << x << ", y=" << y << endl;
swapByReference(x, y);
cout << "引用交换后: x=" << x << ", y=" << y << endl;
return 0;
}
88. 内存泄漏检测示例
#include <iostream>
using namespace std;
class MemoryLeakDemo {
int* data;
public:
MemoryLeakDemo(int size) {
data = new int[size]; // 分配内存
cout << "分配 " << size << " 个整数内存" << endl;
}
// 缺失析构函数会导致内存泄漏
// ~MemoryLeakDemo() { delete[] data; }
};
int main() {
cout << "创建对象..." << endl;
MemoryLeakDemo obj(100);
// 对象销毁时,分配的100个int内存未被释放
cout << "程序结束,内存泄漏发生!" << endl;
return 0;
}
89. 深拷贝与浅拷贝
#include <iostream>
#include <cstring>
using namespace std;
class String {
char* buffer;
int length;
public:
String(const char* str) {
length = strlen(str);
buffer = new char[length + 1];
strcpy(buffer, str);
}
// 深拷贝构造函数
String(const String& other) {
length = other.length;
buffer = new char[length + 1];
strcpy(buffer, other.buffer);
}
// 深拷贝赋值运算符
String& operator=(const String& other) {
if (this != &other) {
delete[] buffer; // 释放原有内存
length = other.length;
buffer = new char[length + 1];
strcpy(buffer, other.buffer);
}
return *this;
}
~String() {
delete[] buffer;
}
void print() const {
cout << buffer << endl;
}
};
int main() {
String s1("Hello");
String s2 = s1; // 调用拷贝构造函数
cout << "s1: "; s1.print();
cout << "s2: "; s2.print();
String s3("World");
s2 = s3; // 调用赋值运算符
cout << "赋值后 s2: "; s2.print();
return 0;
}
90. 动态对象数组
#include <iostream>
using namespace std;
class Student {
string name;
int score;
public:
Student() : name(""), score(0) {}
Student(string n, int s) : name(n), score(s) {}
void display() const {
cout << name << ": " << score << "分" << endl;
}
};
int main() {
int count;
cout << "输入学生人数: ";
cin >> count;
// 动态创建对象数组
Student* students = new Student[count];
// 输入学生信息
for (int i = 0; i < count; i++) {
string name;
int score;
cout << "输入第" << i+1 << "个学生的姓名和分数: ";
cin >> name >> score;
students[i] = Student(name, score);
}
// 显示学生信息
cout << "\n学生列表:" << endl;
for (int i = 0; i < count; i++) {
students[i].display();
}
delete[] students; // 释放对象数组
return 0;
}
91. vector容器基本操作
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> vec = {5, 2, 8, 1, 9};
// 添加元素
vec.push_back(4);
vec.insert(vec.begin() + 2, 7);
// 删除元素
vec.pop_back();
vec.erase(vec.begin() + 1);
// 排序
sort(vec.begin(), vec.end());
// 遍历
cout << "vector内容: ";
for (int num : vec) {
cout << num << " ";
}
// 容量信息
cout << "\n大小: " << vec.size()
<< ", 容量: " << vec.capacity() << endl;
return 0;
}
92. list容器操作
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> myList = {3, 1, 4};
// 插入删除
myList.push_front(2);
myList.push_back(5);
myList.remove(1); // 删除所有值为1的元素
// 排序和去重
myList.sort();
myList.unique();
// 遍历
cout << "list内容: ";
for (int num : myList) {
cout << num << " ";
}
return 0;
}
93. map统计单词频率
#include <iostream>
#include <map>
#include <sstream>
using namespace std;
int main() {
string text = "apple banana apple orange banana apple";
map<string, int> wordCount;
// 分割字符串
istringstream iss(text);
string word;
while (iss >> word) {
wordCount[word]++;
}
// 输出统计结果
cout << "单词频率:\n";
for (const auto& pair : wordCount) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
94. set存储不重复元素
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> uniqueNumbers;
// 插入元素(自动去重)
uniqueNumbers.insert(3);
uniqueNumbers.insert(1);
uniqueNumbers.insert(4);
uniqueNumbers.insert(1); // 重复元素不会被插入
// 遍历
cout << "set内容: ";
for (int num : uniqueNumbers) {
cout << num << " ";
}
// 查找
if (uniqueNumbers.find(4) != uniqueNumbers.end()) {
cout << "\n找到数字4" << endl;
}
return 0;
}
95. STL算法排序
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {5, 2, 8, 1, 9};
// 升序排序
sort(nums.begin(), nums.end());
cout << "升序: ";
for (int num : nums) cout << num << " ";
// 降序排序
sort(nums.begin(), nums.end(), greater<int>());
cout << "\n降序: ";
for (int num : nums) cout << num << " ";
// 部分排序(前3个最小元素)
partial_sort(nums.begin(), nums.begin() + 3, nums.end());
cout << "\n前3小元素: ";
for (int i = 0; i < 3; i++) cout << nums[i] << " ";
return 0;
}
96. 迭代器遍历容器
#include <iostream>
#include <list>
using namespace std;
int main() {
list<string> names = {"Alice", "Bob", "Charlie"};
// 正向迭代器
cout << "正向遍历: ";
for (auto it = names.begin(); it != names.end(); ++it) {
cout << *it << " ";
}
// 反向迭代器
cout << "\n反向遍历: ";
for (auto rit = names.rbegin(); rit != names.rend(); ++rit) {
cout << *rit << " ";
}
return 0;
}
97. stack实现括号匹配
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isBalanced(const string& expr) {
stack<char> s;
for (char c : expr) {
if (c == '(' || c == '[' || c == '{') {
s.push(c);
} else if (c == ')' || c == ']' || c == '}') {
if (s.empty()) return false;
char top = s.top();
s.pop();
if ((c == ')' && top != '(') ||
(c == ']' && top != '[') ||
(c == '}' && top != '{')) {
return false;
}
}
}
return s.empty();
}
int main() {
string expr = "{([a+b]*[c-d])/e}";
cout << expr << (isBalanced(expr) ? " 括号匹配" : " 括号不匹配") << endl;
return 0;
}
98. queue模拟排队系统
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<string> customers;
// 入队
customers.push("顾客1");
customers.push("顾客2");
customers.push("顾客3");
// 服务过程
while (!customers.empty()) {
cout << "正在服务: " << customers.front() << endl;
customers.pop();
cout << "剩余排队人数: " << customers.size() << endl;
}
return 0;
}
99. priority_queue优先级调度
#include <iostream>
#include <queue>
using namespace std;
int main() {
// 默认大顶堆
priority_queue<int> maxHeap;
// 小顶堆
priority_queue<int, vector<int>, greater<int>> minHeap;
// 添加元素
for (int num : {3, 1, 4, 1, 5}) {
maxHeap.push(num);
minHeap.push(num);
}
// 输出
cout << "大顶堆出队: ";
while (!maxHeap.empty()) {
cout << maxHeap.top() << " ";
maxHeap.pop();
}
cout << "\n小顶堆出队: ";
while (!minHeap.empty()) {
cout << minHeap.top() << " ";
minHeap.pop();
}
return 0;
}
100. Lambda表达式排序
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<pair<string, int>> products = {
{"手机", 2500}, {"电脑", 5000}, {"平板", 3000}
};
// 按价格升序排序
sort(products.begin(), products.end(),
const auto& a, const auto& b {
return a.second < b.second;
});
cout << "按价格排序:\n";
for (const auto& p : products) {
cout << p.first << ": " << p.second << "元\n";
}
// 按名称长度降序排序
sort(products.begin(), products.end(),
const auto& a, const auto& b {
return a.first.length() > b.first.length();
});
cout << "\n按名称长度排序:\n";
for (const auto& p : products) {
cout << p.first << ": " << p.second << "元\n";
}
return 0;
}
更多推荐
所有评论(0)