c++

如何在C++中实现table的增删改查

小樊
83
2024-09-07 04:57:42
栏目: 编程语言

在C++中,可以使用std::mapstd::unordered_map来实现一个简单的表(table),并进行增删改查操作。下面是一个简单的示例:

首先,需要包含相应的头文件:

#include<iostream>
#include <map>
#include<string>

接下来,定义一个类来表示表格中的数据:

class Record {
public:
    std::string name;
    int age;
};

然后,创建一个std::mapstd::unordered_map来存储表格数据:

std::map<int, Record> table;

接下来,实现增删改查操作:

  1. 插入(增):
void insert(int id, const std::string& name, int age) {
    Record record;
    record.name = name;
    record.age = age;
    table[id] = record;
}
  1. 删除(删):
void deleteRecord(int id) {
    auto it = table.find(id);
    if (it != table.end()) {
        table.erase(it);
    } else {
        std::cout << "Record not found."<< std::endl;
    }
}
  1. 修改(改):
void update(int id, const std::string& newName, int newAge) {
    auto it = table.find(id);
    if (it != table.end()) {
        it->second.name = newName;
        it->second.age = newAge;
    } else {
        std::cout << "Record not found."<< std::endl;
    }
}
  1. 查询(查):
void search(int id) {
    auto it = table.find(id);
    if (it != table.end()) {
        std::cout << "ID: " << it->first << ", Name: " << it->second.name << ", Age: " << it->second.age<< std::endl;
    } else {
        std::cout << "Record not found."<< std::endl;
    }
}

最后,编写主函数来测试这些操作:

int main() {
    insert(1, "Alice", 30);
    insert(2, "Bob", 25);
    insert(3, "Charlie", 22);

    search(1);
    search(4);

    update(1, "Alicia", 31);
    search(1);

    deleteRecord(2);
    search(2);

    return 0;
}

这个示例展示了如何在C++中使用std::map实现一个简单的表格,并进行增删改查操作。注意,这里使用了int作为键值,但也可以使用其他类型作为键值。

0
看了该问题的人还看了