[英]Algorithm forward_list is sorted?
I have some difficulties in C++11. 我在C ++ 11中遇到一些困难。 I would like to create function
isSorted
which return true if my std::forward_list
is sorted, and false if not. 我想创建一个
isSorted
函数,如果对我的std::forward_list
进行排序,则返回true;否则,返回false。
I have imagined code like this: 我想象过这样的代码:
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();
}
But gcc return me a segmentation fault surrounding the while line. 但是gcc给我返回了while线周围的分段错误。
Your code will fail if the iterator reaches the last element in the list. 如果迭代器到达列表中的最后一个元素 ,则代码将失败。 When that happens
std::next(it)
is equal to list.end()
and it's an error to dereference an end()
iterator (causing a segfault in this case). 发生这种情况时,
std::next(it)
等于list.end()
并且取消引用end()
迭代器是错误的end()
在这种情况下会导致段错误)。
My suggestion is to use the std::is_sorted
algorithm in the standard library. 我的建议是在标准库中使用
std::is_sorted
算法。 It's already written, debugged, and does what you want. 它已经被编写,调试并且可以执行您想要的操作。
template<class T>
bool estTriee(const std::forward_list<T>& list) {
return std::is_sorted(list.begin(), list.end());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.