Containers list
作者:
xianhai
,
2021-11-22 14:22:31
,
所有人可见
,
阅读 227
#include <iostream>
#include <list>
using namespace std;
// a predicate implemented as a function:
bool single_digit (const int& value) { return (value < 10); }
// a predicate implemented as a class:
struct is_odd {
bool operator() (const int& value) { return (value % 2) == 1; }
};
void print(list<int> &l1) {
for (auto it = l1.begin(); it != l1.end(); it++) {
cout << *it << ' ';
}
cout << endl;
}
void print2(list<int> &l1) {
for (auto &x : l1) {
cout << x << ' ';
}
cout << endl;
}
int main() {
int myints[] = {1, 2, 3, 4};
list<int> l1(myints, myints + sizeof(myints) / sizeof(int));
cout << "sizeof(myints)=" << sizeof myints << endl;
cout << "sizeof(int)=" << sizeof(int) << endl;
for (list<int>::iterator it = l1.begin(); it != l1.end(); it++) {
cout << *it << ' ';
}
cout << endl;
// 添加
l1.push_front(0);
l1.push_back(6);
l1.push_back(5);
l1.push_back(6);
l1.push_back(11);
list<int>::iterator it0;
it0 = l1.begin();
std::advance(it0, 3);
l1.insert (it0, 2, 20);
// auto
print(l1);
cout << l1.size() << ' ' << l1.max_size() << endl;
//
l1.sort();
l1.unique();
print(l1);
//
l1.reverse();
print(l1);
//
l1.remove_if (is_odd());
print2(l1);
return 0;
}
运行结果
sizeof(myints)=16
sizeof(int)=4
1 2 3 4
0 1 2 20 20 3 4 6 5 6 11
11 768614336404564650
0 1 2 3 4 5 6 11 20
20 11 6 5 4 3 2 1 0
20 6 4 2 0
详见
http://cpp.sh/