C++使用STL容器删除奇数并排序(vector,list,forward_list,deque,priority_queue)
vector.cpp
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
vector<int> vec = { 2,8,3,4,9,7,5,6,1,10 };
auto ve = vec.begin();
while (ve != vec.end())
{
if (!(*ve % 2)) {
++ve;
}
else {
ve = vec.erase(ve);
}
}
for (auto v : vec) {
cout << v << " ";
//vector<int> vec(v, v + 10);
}
cout << endl;
sort(vec.begin(), vec.end());
for (vector<int>::iterator it = vec.begin(); it != vec.end(); it++) {
cout <<*it << " ";
}
return 0;
}
list.cpp
#include<algorithm>
#include<list>
#include<iostream>
using namespace std;
std::ostream& operator<<(std::ostream& ostr, const std::list<int>& list)
{
for (auto& i : list) {
ostr << " " << i;
}
return ostr;
}
int main()
{
list<int> li = { 2,8,3,4,9,7,5,6,1,10 };
auto it = li.begin();
while (it != li.end())
{
if (*it % 2)
it = li.erase(it);
else
++it;
}
for (auto i : li) {
cout << i << " ";
}
cout << endl;
li.sort();
cout << li << endl;
return 0;
}
forward_list.cpp
#include<algorithm>
#include <iostream>
#include <forward_list>
using namespace std;
bool ilst(const int& first, const int& second) {
return first < second;
}
int main()
{
forward_list<int> lst{ 2,8,3,4,9,7,5,6,1,10 };
auto iter_begin = lst.before_begin();
auto iter = lst.begin();
while (iter != lst.end())
{
if (*iter % 2 == 1)
{
iter = lst.erase_after(iter_begin);
}
else
{
iter_begin++;
iter++;
}
}
for (auto it : lst)
cout << it << " ";
cout << endl;
lst.sort(ilst);
for (auto it : lst) {
cout << it << " ";
}
return 0;
}
deque.cpp
#include <iostream>
#include <deque>
#include<algorithm>
using namespace std;
int main()
{
deque<int> dp = { 2,8,3,4,9,7,5,6,1,10 };
auto it = dp.begin();
while (it != dp.end()) {
if (*it % 2) {
it = dp.erase(it);
}
else {
it++;
}
}
for (auto i : dp)
cout << i << " ";
cout << endl;
sort(dp.begin(), dp.end());
for (deque<int>::iterator it = dp.begin(); it != dp.end(); it++) {
cout << *it << " ";
}
return 0;
}
priority_queue.cpp
#include <iostream>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
priority_queue<int ,vector<int>,greater<int>>p;
p.push(2), p.push(8), p.push(3), p.push(4), p.push(9), p.push(7), p.push(5), p.push(6), p.push(1), p.push(10);
for (int i = 0; i < 10; i++) {
cout << p.top()<<" ";
p.pop();
}
cout << endl;
//priority_queue<int, vector<int>, greater<int>>p1;
p.push(2), p.push(8), p.push(3), p.push(4), p.push(9), p.push(7), p.push(5), p.push(6), p.push(1), p.push(10);
while (!p.empty()) {
if (!(p.top() % 2) == 0) {
p.pop();
}
else {
cout << p.top() << " ";
p.pop();
}
}
return 0;
}