C++ 当只有一个元素发生变化时,如何在排序列表中进行快速排序
我需要一个总是排序的元素列表。所涉及的操作非常简单,例如,如果列表从高到低排序,则在某个循环任务中,我只需要三个操作:C++ 当只有一个元素发生变化时,如何在排序列表中进行快速排序,c++,list,C++,List,我需要一个总是排序的元素列表。所涉及的操作非常简单,例如,如果列表从高到低排序,则在某个循环任务中,我只需要三个操作: while true do { list.sort() //sort the list that has hundreds of elements val = list[0] //get the first/maximum value in the list list.pop_front() //remove the first/maximum elem
while true do {
list.sort() //sort the list that has hundreds of elements
val = list[0] //get the first/maximum value in the list
list.pop_front() //remove the first/maximum element
...//do some work here
list.push_back(new_elem)//insert a new element
list.sort()
}
但是,由于我一次只添加一个元素,而且我有速度方面的考虑,所以我不希望排序遍历所有元素,例如使用冒泡排序。我只是想知道是否有一个函数可以按顺序插入元素?或者list::sort()函数是否足够聪明,可以在只添加/修改一个元素时使用某种快速排序?
或者如果以上都是需要的操作,我应该使用deque以获得更好的速度性能吗
非常感谢 如评论中所述,如果您没有被锁定在
std::list
中,那么您应该尝试std::set
或std::multiset
std::list::insert
方法采用迭代器,指定在何处添加新项。您可以使用std::lower_bound
找到正确的插入点;如果没有随机访问迭代器,它不是最优的,但它仍然只进行O(logn)比较
注意:不要使用与内置类冲突的变量名,如list
lst.sort(std::greater<T>()); //sort the list that has hundreds of elements
while true do {
val = lst.front(); //get the first/maximum value in the list
lst.pop_front(); //remove the first/maximum element
...//do some work here
std::list<T>::iterator it = std::lower_bound(lst.begin(), lst.end(), std::greater<T>());
lst.insert(it, new_elem); //insert a new element
// lst is already sorted
}
lst.sort(std::greater())//对包含数百个元素的列表进行排序
尽管如此{
val=lst.front();//获取列表中的第一个/最大值
lst.pop_front();//删除第一个/最大值元素
…//在这里做些工作
std::list::iterator it=std::下限(lst.begin()、lst.end()、std::greater());
lst.insert(it,new_elem);//插入新元素
//lst已排序
}
如果您所做的只是一次弹出一个元素,一次推一个元素,那么听起来您需要一个堆;不是已排序的列表。您是否考虑过?如果需要按顺序排序,请考虑使用<代码> STD::SET。新元素的插入将是O(logn)
。似乎列表不是std::list,但更像是std::vector。我建议std::lower_boundlist::sort
不知道列表的先决条件,因此无法针对您的特殊情况进行优化。