std::sort面试
时间: 2023-08-25 13:15:56 浏览: 293
回答: 在C++中使用std::sort函数对容器进行排序是一种常见的操作。可以直接调用std::sort函数,并传入起始迭代器和结尾迭代器来对容器进行排序。例如,可以使用以下代码对deque容器进行排序:
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
template<typename T>
void sort_stdalg(deque<T>& dq) {
std::sort(dq.begin(),dq.end());
}
int main() {
deque<int> dq = {4, 2, 3, 1};
sort_stdalg(dq);
for (int num : dq) {
cout << num << " ";
}
// 输出: 1 2 3 4
return 0;
}
< sorted[j - 1]) {
T t = sorted[j];
sorted[j = sorted[j - 1];
sorted[j - 1 = t;
}
}
}
return sorted;
}
int main() {
constexpr std::array<int, 4> before{4, 2, 3, 1};
constexpr std::array<int, 4> after = Sort(before);
static_assert(after == 1);
static_assert(after == 2);
static_assert(after == 3);
static_assert(after == 4);
return 0;
}
<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [用std::map、std::sort、冒泡对deque进行排序(C/C++)](https://blog.csdn.net/brahmsjiang/article/details/79504707)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [C++语言中std::array的神奇用法总结,你需要知道!](https://blog.csdn.net/qq_40442753/article/details/110464532)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文