[英]Algorithm forward_list is sorted?
我在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線周圍的分段錯誤。
如果迭代器到達列表中的最后一個元素 ,則代碼將失敗。 發生這種情況時, std::next(it)
等於list.end()
並且取消引用end()
迭代器是錯誤的end()
在這種情況下會導致段錯誤)。
我的建議是在標准庫中使用std::is_sorted
算法。 它已經被編寫,調試並且可以執行您想要的操作。
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.