如何在C++中實(shí)現(xiàn)table的增刪改查

c++
小樊
83
2024-09-07 04:57:42

在C++中,可以使用std::mapstd::unordered_map來(lái)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的表(table),并進(jìn)行增刪改查操作。下面是一個(gè)簡(jiǎn)單的示例:

首先,需要包含相應(yīng)的頭文件:

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

接下來(lái),定義一個(gè)類(lèi)來(lái)表示表格中的數(shù)據(jù):

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

然后,創(chuàng)建一個(gè)std::mapstd::unordered_map來(lái)存儲(chǔ)表格數(shù)據(jù):

std::map<int, Record> table;

接下來(lái),實(shí)現(xiàn)增刪改查操作:

  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;
    }
}

最后,編寫(xiě)主函數(shù)來(lái)測(cè)試這些操作:

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;
}

這個(gè)示例展示了如何在C++中使用std::map實(shí)現(xiàn)一個(gè)簡(jiǎn)單的表格,并進(jìn)行增刪改查操作。注意,這里使用了int作為鍵值,但也可以使用其他類(lèi)型作為鍵值。

0