东阳的学习笔记
你可以使用字符串或数组作为 STL 容器, 也可以自行撰写特殊容器以满足特殊需求。如果你自行撰写容器, 仍可从诸如排序、合并算法中受益。此即 开放型封闭原则。
将自定义的容器 “STL化” 的三种不同方法
The invasive approach (侵入式作法)
直接提供 STL 容器的所需接口。 这种做法需要以特定方式编写容器,所以是侵入性的。
The noninvasive approach (非侵入式作法)
由你撰写或提供特殊的迭代器, 作为算法和特殊容器间的界面。他需要的只是 “遍历容器所有元素“的能力——这是任何容器都能以某种形式展现的能力。
The wrapper approach(包装法)
将上述两种方法加以组合,我们可以写一个外套类别(wrapper)来包装任何的数据结构, 并显示出与 STL 容器相似的接口
直接使用数组当作 STL 的例子
/*
* array1.cpp
* 以 array 作为STL容器
* Created on: 2021年1月8日
* Author: san
*/
#include <iostream>
#include <algorithm>
#include <functional>
#include <iterator>
using namespace std;
int main()
{
int coll[] {5, 6, 2, 4, 1, 3};
// square all elements,
transform(coll, coll+6, // first source
coll, // second source
coll, // dest
multiplies<int>()); // operation
// sort begining with the second element
sort(coll+1, coll+6);
// print all
copy(coll, coll+6,
ostream_iterator<int>(cout, " "));
cout << endl;
}
一个数组外包装的例子
/*
* carray.hpp
*
* Created on: 2021年1月8日
* Author: san
*/
#ifndef CONT_CARRAY_HPP_
#define CONT_CARRAY_HPP_
#include <cstddef>
template <class T, std::size_t thesize>
class carray {
private:
T v[thesize];
public:
// type definition
typedef T value_type;
typedef T *iterator;
typedef const T *const_iterator;
typedef T &reference;
typedef const T &const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
// iterator support
iterator begin() { return v; }
const_iterator begin() const { return v; }
iterator end() { return v + thesize; }
const_iterator end() const { return v + thesize; }
// direct element access
reference operator[] (size_type i) { return v[i]; }
const_reference operator[] (size_type i) const { return v[i]; }
// size is constant
size_type size() const { return thesize; }
size_type max_size() const { return thesize; }
// conversion to ordinary array
T *as_array() { return v; }
};
#endif /* CONT_CARRAY_HPP_ */
本文介绍了如何将自定义容器与STL(标准模板库)结合,包括侵入式、非侵入式和包装法三种方法。示例展示了使用数组作为STL容器以及创建一个包装类carray,实现类似STL接口,支持算法操作如排序和转换。这些方法使自定义数据结构能够利用STL的便利性和效率。
347

被折叠的 条评论
为什么被折叠?



