如何用容器列表实现函数

How to implement functions with container list

本文关键字:实现 函数 列表 何用容      更新时间:2023-10-16

我正在学习容器列表。我想写一个函数来替换(索引上的元素)插入(索引上的元素)我想知道如何删除它们。我学习这个大概有两天了,我看了一些视频,读了一些文章,但是我就是不知道怎么写这个代码。我知道list和指针的关系

这是我的想象(这只是一个开始)

void replace(list<Contact> &listOf, int index, const Contact &information) {
    for(list<int>::iterator it = listOf.begin(); it != listOf.end(); it++){
    }
}

我不知道for循环是否写对了,但我想象它会遍历list,如果它找到想要替换它的索引,它就会覆盖。

我认为函数insert有相同的参数

这就是我想象的删除它的方式,但我不确定如何实现。

Contact delete(list<Contact> &listOf, int index) {
}

我已经在程序开始时创建了带有姓名和姓氏的联系人结构。

循环应该写为

for (list<Contact>::iterator it = listOf.begin(); it != listOf.end(); ++it) {
    do what you wan't with *it.
}

列表没有随机访问,因此不适合进行这种操作。如果你坚持,这里有一个避免自己编写循环的方法:

void replace(list<Contact> &listOf, int index, const Contact &information) {
    list<int>::iterator it = listOf.begin();
    std::advance(it, index);
    *it = information;
}

使用std::vector进行随机访问操作。使用std::list在容器中间进行插入或删除等修改