STL扩展——编写自己的 STL 容器

本文介绍了如何将自定义容器与STL(标准模板库)结合,包括侵入式、非侵入式和包装法三种方法。示例展示了使用数组作为STL容器以及创建一个包装类carray,实现类似STL接口,支持算法操作如排序和转换。这些方法使自定义数据结构能够利用STL的便利性和效率。
摘要由CSDN通过智能技术生成

东阳的学习笔记

你可以使用字符串或数组作为 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_ */

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东阳z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值