The Standard Template Library (STL) is a set of C++ template classes to provide grogramming data structures and functions such as lists, stacks, arrays, etc.
STL has 4 components
- Algorithms
- Containers
- Functions
- Iterators
STL_Allocator
Allocator.h
/*
* @Author: Kelpie_Banshee
* @Date: 2022-09-14 18:49:17
* @LastEditors: Kelpie_Banshee
* @LastEditTime: 2022-09-14 19:22:28
* @FilePath: /C++/STL/Allocator/2_1_1Singalloc.h
* @Description:
* Pwn Plan of Learning STL
* Copyright (c) 2022 by StarGrandp4 [email protected], All Rights Reserved.
*/
#ifndef __SingALLOC__
#define __SingALLOC__
#include <new> // For new
#include <cstddef> // size_t
#include <cstdlib> // for exit()
#include <climits>
#include <iostream>
using namespace std;
namespace Sing
{
// Allocate the memory
template <class T>
inline T *_allocate(ptrdiff_t size, T *)
{
set_new_handler(0);
T *tmp = (T *)(::operator new((size_t)(size * sizeof(T))));
if (tmp == 0)
{
cerr << "out of memory" << endl;
exit(1);
}
return tmp;
}
// Deallocate the memory
template <class T>
inline void _deallocate(T *buffer)
{
::operator delete(buffer);
}
// new
template <class T1, class T2>
inline void _construct(T1 *p, const T2 &value)
{
new (p) T1(value);
}
// destory
template <class T>
inline void _destroy(T *ptr)
{
ptr->~T();
}
template <class T>
class allocator
{
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
// rebind allocator of type U
template <class U>
struct rebind
{
typedef allocator<U> other;
};
pointer allocate(size_type n, const void *hint = 0)
{
return _allocate((difference_type)n, (pointer)0);
}
void deallocate(pointer p, const T &value)
{
_deallocate(p);
}
void construct(pointer p, const T &value)
{
_construct(p, value);
}
void destory(pointer p)
{
_destroy(p);
}
const_pointer ret_addr(reference x)
{
return (pointer)&x;
}
const_pointer ret_const_addr(const_reference x)
{
return (const_pointer)&x;
}
size_type max_size() const
{
return size_type(UINT_MAX / sizeof(T));
}
};
}
#endif
Allocator.cpp
/*
* @Author: Kelpie_Banshee
* @Date: 2022-09-14 19:09:59
* @LastEditors: Kelpie_Banshee
* @LastEditTime: 2022-09-14 19:25:12
* @FilePath: /C++/STL/Allocator/2_1_1Singalloc.cpp
* @Description:
* Copyright (c) 2022 by StarGrandp4 [email protected], All Rights Reserved.
*/
#include "2_1_1Singalloc.h"
#include <vector>
#include <iostream>
#define __ALIGN 8
using namespace std;
int round_up(int b){
return(((b) + __ALIGN -1) &~ (__ALIGN -1));
}
int main(){
int a[5] = {1,2,3,4,5};
int i;
vector<int, Sing::allocator<int> >v(a, a+5);
for(i=0; i<v.size(); i++){
cout << v[i] << endl;
}
return 0;
}