使用forward_list创建一个字母列表

Creating an alphabetic list using forward_list

本文关键字:一个 列表 forward list 创建 使用      更新时间:2023-10-16

我正在尝试使用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;
      }
    }
  }
}