stl三大组件
- 容器
- 算法
algorithm
- 迭代器,每个容器有专属的迭代器
常用容器
string
容器,char*
是一个指针,string
是一个类。
void func_string() {
string s = "hello world";
s += " liangze";
s.append(" hi");
s.replace(s.rfind("ze"), 2, "***");
for (int i = 0; i < s.size(); i++) {
// cout << s.at(i) << endl;
}
cout
<< s.substr(1,6) << '\t'
<< string("abc").compare("bbc") << "\t" << s.rfind("li") << '\t' << s << endl;
//string和c-style转换
const char *p = s.c_str();
string s2 = p, s3(p), s4{ p };
}
vector
容器,和array区别在于空间运用的灵活性。线性,单端数组。
void func_vector() {
vector
int arr[] = {2,3,4,5,6,7};
vector
vector
vector
v.assign(v2.begin(), v2.end());
cout << v.capacity() << "\t" << v.back() << endl;
v.resize(3);
vector<int>(v).swap(v);//用的size开辟空间
v.insert(v.end(), 10, 100);
cout << v.capacity() << "\t" << v.back() << endl;
}
deque
容器,双端数组
void printDeque(const deque<int>&d) {
for (deque<int>::const_iterator it = d.begin(); it != d.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
void func_deque() {
deque<int> d;
d.push_back(10);
d.push_back(20);
d.push_back(30);
d.push_back(40);
printDeque(d);
d.push_back(100);
d.push_front(200);
printDeque(d);
d.pop_front();
printDeque(d);
}
stack
容器。栈容器没有迭代器。先进后出。
void func_stack() {
stack<int>s;
s.push(10);
s.push(20);
s.push(30);
cout << s.size() << endl;
while (s.size() != 0) {
cout << s.top() << endl;
s.pop();
}
cout << s.size() << endl;
}
queue
容器。没有迭代器。先进先出。
void func_queue() {
queue<int>q;
q.push(10);
q.push(20);
q.push(30);
cout << q.size() << endl;
while (!q.empty()) {
cout << q.front() << " " << q.back() << endl;
q.pop();
}
cout << q.size() << endl;
}
list
容器。双向循环链表,非连续存储空间。
void printList(const list<int>&L) {
for (list<int>::const_iterator it = L.begin(); it != L.end(); it++) {
cout << *it << " ";
}
cout << endl;
}
void func_list() {
list<int>L;
for (int i = 0; i < 10; i++) {
L.push_back(i);
}
printList(L);
L.pop_front();
L.pop_back();
L.insert(L.begin(), 1000);
L.push_front(5);
printList(L);
L.remove(5);
printList(L);
}
set/multiset
容器,multiset
允许重复。关联值容器
#include <set>
void func_set() {
set<int>s;
s.insert(1);
s.insert(2);
s.insert(2);
set<int>::iterator pos = s.find(2);
if (pos != s.end()) {
// 找到
}
cout << s.size() << endl;
pair<set<int>::iterator, set<int>::iterator> ret = s.equal_range(3);
if (ret.first != s.end()) {
//找到
}
}
map
容器
void func_map() {
map<int, int>m;
m.insert(make_pair(1, 10));
m[2] = 20;
}
常用算法
- 函数对象
class Person {
public:
int count = 0;
void operator()(int num) {
count++;
std::cout << count << "\t" << num << std::endl;
}
};
int main() {
std::cout << "main" << std::endl;
Person p;
p(123);
p(123);
p(423);
return 0;
};
-
谓词,指普通函数或重载
operator
返回是bool
类型 的函数对像,如果operator
接受一个参数,就叫一元谓词
,接受两个参数就叫二元谓词
,谓词可作为一个判断式。 -
内建函数,需要导入
#iclude <functional>