使用forward_list创建一个字母列表
Creating an alphabetic list using forward_list
我正在尝试使用forward_list创建一个Alpabethic排序列表。该计划是将所有元素与我要插入列表中的元素进行比较,如果它大于元素,则将其插入。但是问题在于,我无法找到一种在最后一个元素之后插入元素的方法。我已经搜索过它,我只得到答案,说我应该避免forward_list ...
所以问题是,我该如何做这项工作...
void insertOrdered(std::forward_list<Person> &l, const Person& p) {
auto i = l.begin();
if (l.empty()) {
//placing an element at the front if the list is empty
l.emplace_front(p);
return;
}
for (i; i != l.end(); ) {
if (p < *i) {
//Moving the element at position i to the position after i.
l.insert_after(i, *i);
//placing person at i
*i = p;
return;
}
else{
i++;
}
}
//Trying to insert after the last element
l.emplace_front(l.end(), p);
}
实施&lt;操作员:
bool Person::operator<(Person& rhs) {
if (this->firstname < rhs.firstname) {
return true;
}
else {
return false;
}
}
我认为诀窍在于循环内您必须保留迭代器,然后再移动下一个元素。例如:
void insertOrdered(std::forward_list<int> &l, const Person& p) {
if (l.empty()) {
l.emplace_front(p);
return;
}
for (auto i=l.begin(); i!= l.end();) {
auto m = i; // keep the current iterator i to m.
if (p < *i) {
l.insert_after(i, *i);
*i = p;
return;
}
else {
i++; // increase the iterator i
if (i == l.end()) {
l.emplace_after(m,p); // use m to add data to the last element
return;
}
}
}
}
相关文章:
- 链表,将列表复制到另一个列表
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 我如何创建一个列表,然后从中创建两个列表,其中一个用于偶数,另一个用于奇数?
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- 打印一个列表给出错误,指出迭代器不可递减
- C++:从两个包含子类 (typedef) 的列表创建一个列表
- 在 std 列表中查找对象并将其添加到另一个列表
- 在c++中遍历一个列表并在另一个列表中搜索每个元素
- 我在 C++ 中创建了一个列表容器类,但它没有按预期工作
- 如何通过赋值运算符重载将一个列表复制到另一个列表上?C++
- 正在将指针复制到assign运算符中的另一个列表元素
- 在c++中传递一个列表作为返回类型
- 如何在c++中创建一个列表及其内容常量
- C++:如何将迭代器设置为另一个列表中的结构内的列表
- C++ std::sort 引用另一个列表的自定义比较函数
- 如何让数组在下一次输入之前显示数组内容的前一个列表?
- 如果我创建一个列表:<T>:迭代器,有没有办法重载++(增量)运算符?
- 我如何解码一个列表的列表
- 如何在c++中用一个目录中的所有文件夹填充一个列表框
- c++遍历一个列表来调用某个函数