如何用容器列表实现函数
How to implement functions with container list
我正在学习容器列表。我想写一个函数来替换(索引上的元素)插入(索引上的元素)我想知道如何删除它们。我学习这个大概有两天了,我看了一些视频,读了一些文章,但是我就是不知道怎么写这个代码。我知道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
在容器中间进行插入或删除等修改
相关文章:
- 在命名空间内部还是外部实现 c++ 函数?
- 如何在C++中实现函数(f)(x)(y, z)(g)(r)
- 如何在C++中实现函数上的二叉搜索?
- 键按下事件错误 Qt 实现函数时
- 在子类之外实现函数导致未知错误
- 通过模板滥用实现函数式C++
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 我正在尝试创建自己的 strcat() 函数,而不是使用库实现函数<cstring>
- 如果未实现函数,则在链接时启用错误
- 用函数参数实现c++函数指针
- 如何在Android SDK中调用和实现C++函数
- 在 C++ RCPP 中实现 R 函数
- 实现函数模板填充多维对象
- 类的层次结构,试图在基本级别实现函数
- 用c++实现函数对象的自动检测类型
- 用shared_ptrs实现函数模板的C++实例化
- 在类中实现函数导致错误:成员引用基类型'ifstream (string)'不是结构或联合
- 用c++实现S函数.生成错误
- 引用可以用于实现函数重写吗
- 如何在c++中实现函数超时