制作一个通讯录,利用顺序存储结构(或者链式存储结构)实现电话本的基本操作,比如通讯录的建立、插入记录、删除记录、修改记录、查找记录和输出通讯录等操作。(功能不限于所述这些)使用C++实现;写出完整代码
时间: 2024-10-21 16:08:20 浏览: 40
在C++中,我们可以选择使用数组作为顺序存储结构来实现一个简单的通讯录。这里我们假设每个联系人信息由姓名、电话号码组成,可以用一个struct表示。链表也可以用于存储,但是由于题目强调了基本操作,这里先演示顺序存储。
```cpp
#include <iostream>
#include <string>
// 定义联系人信息
struct Contact {
std::string name;
std::string phone_number;
// 构造函数
Contact(const std::string& n, const std::string& p) : name(n), phone_number(p) {}
};
class AddressBook {
private:
Contact contacts[100]; // 顺序存储最多100条记录,可根据需要调整大小
int size; // 当前记录的数量
public:
// 初始化空通讯录
AddressBook() : size(0) {}
// 添加联系人
void addContact(const std::string& name, const std::string& phone) {
if (size == 99) {
std::cout << "通讯录已满,无法添加更多联系人。\n";
return;
}
contacts[size] = Contact(name, phone);
size++;
}
// 删除联系人(通过索引)
bool deleteContact(int index) {
if (index >= 0 && index < size) {
for (int i = index; i < size - 1; ++i)
contacts[i] = contacts[i + 1];
size--;
return true;
}
else
std::cout << "无效的索引。\n";
return false;
}
// 修改联系人(通过索引)
bool modifyContact(int index, const std::string& new_name, const std::string& new_phone) {
if (index >= 0 && index < size) {
contacts[index].name = new_name;
contacts[index].phone_number = new_phone;
return true;
}
else
std::cout << "无效的索引。\n";
return false;
}
// 查找联系人
Contact* findContact(const std::string& name) {
for (int i = 0; i < size; ++i)
if (contacts[i].name == name)
return &contacts[i];
return nullptr;
}
// 输出通讯录
void printAddressBook() {
std::cout << "通讯录:\n";
for (int i = 0; i < size; ++i) {
std::cout << "名称: " << contacts[i].name << ", 电话: " << contacts[i].phone_number << "\n";
}
}
};
int main() {
AddressBook book;
book.addContact("Alice", "12345678");
book.addContact("Bob", "98765432");
book.printAddressBook();
// 修改和删除操作(略)
return 0;
}
```
阅读全文
相关推荐


















