算法forward_list是排序的?

时间:2016-01-06 23:24:22

标签: c++ algorithm sorting c++11 forward-list

我在C ++ 11中遇到了一些困难。我想创建函数isSorted,如果我的std::forward_list已排序,则返回true,否则返回false。

我想象过这样的代码:

template<class T>
bool estTriee(forward_list<T>& list) {
        typename forward_list<T>::iterator it;
        it = list.begin();

        while(it != list.end() &&  *it <= *next(it, 1)) {
            it++;
        }

        return it == list.end();
}

但是gcc给我留下了围绕while行的分段错误。

1 个答案:

答案 0 :(得分:6)

如果迭代器到达列表中的 last element ,您的代码将失败。当发生这种情况时std::next(it)等于list.end()并且取消引用end()迭代器(在这种情况下导致段错误)是错误的。

我的建议是在标准库中使用std::is_sorted算法。它已经编写,调试,并做你想要的。

template<class T>
bool estTriee(const std::forward_list<T>& list) {
    return std::is_sorted(list.begin(), list.end());
}