STL之针对自定义类型的操作

对于四种关联式容器而言,它们的模板参数中都有一个 Compare ,默认采用的是std:: less ,所以如果 Key 是自定义类型,需要自己传递 Compare 类型的参数才能满足条件,否则无法通过编译。下面以自定义类型Point 为例,以点到原点的距离为标准进行比较。
改写的方式有三种:模板的特化、运算符的重载(小于符号的重载)、函数对象的写法。
#include <math.h>
#include <iostream>
#include <ostream>
#include <set>

using std::cout;
using std::endl;
using std::set;

template <typename Container>
void display(const Container &con)
{
    for(auto &elem : con)
    {
        cout << elem << "  ";
    }
    cout << endl;
}

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
    }

    double getDistance() const
    {
        /* sqrt(pow(_ix, 2) + pow(_iy, 2)); */
        return hypot(_ix, _iy);
    }

    int getX() const
    {
        return _ix;
    }

    int getY() const
    {
        return _iy;
    }

    ~Point()
    {

    }

    friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
    friend bool operator<(const Point &lhs, const Point &rhs);
    friend struct ComparePoint;
private:
    int _ix;
    int _iy;
};

std::ostream &operator<<(std::ostream &os, const Point &rhs)
{
    os << "(" << rhs._ix
       << ", " << rhs._iy
       << ")"; 

    return os;
}

//小于符号的重载
bool operator<(const Point &lhs, const Point &rhs)
{
    cout << "bool operator<" << endl;
    if(lhs.getDistance() < rhs.getDistance())
    {
        return true;
    }
    else if(lhs.getDistance() == rhs.getDistance())
    {
        if(lhs._ix < rhs._ix)
        {
            return true;
        }
        else if(lhs._ix == rhs._ix)
        {
            if(lhs._iy < rhs._iy)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

//y + n(目标行号) + G  复制
//d + n(目标行号) + G  删除
//函数对象的写法
struct ComparePoint
{
    bool operator()( const Point& lhs, const Point& rhs ) const
    {
        cout << "bool ComparePoint" << endl;
        if(lhs.getDistance() < rhs.getDistance())
        {
            return true;
        }
        else if(lhs.getDistance() == rhs.getDistance())
        {
            if(lhs._ix < rhs._ix)
            {
                return true;
            }
            else if(lhs._ix == rhs._ix)
            {
                if(lhs._iy < rhs._iy)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
};


//命名空间的扩展
namespace std
{
//模板的特化
template <>
struct less<Point>
{
    bool operator()(const Point &lhs, const Point &rhs) const
    {
        cout << "template <> struct less" << endl;
        if(lhs.getDistance() < rhs.getDistance())
        {
            return true;
        }
        else if(lhs.getDistance() == rhs.getDistance())
        {
            if(lhs.getX() < rhs.getX())
            {
                return true;
            }
            else if(lhs.getX() == rhs.getX())
            {
                if(lhs.getY() < rhs.getY())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
};

}//end of namespace std

void test()
{
    set<Point> number = {
    /* set<Point, ComparePoint> number = { */
        Point(1, 2),
        Point(1, -2),
        Point(-1, 2),
        Point(1, 2),
        Point(3, 2),
    };
    display(number);
}

int main(int argc, char *argv[])
{
    test();
    return 0;
}

### C++ 自定义类型内存分配方法 #### 使用 `operator new` 和 `operator delete` 对于自定义类型的对象,可以通过重载全局或类作用域内的 `operator new` 和 `operator delete` 来实现自定义的内存分配逻辑。这允许开发者完全掌控对象创建和销毁时所使用的内存位置。 当希望改变整个应用程序中某一类型实例化的方式时,通常会考虑覆盖全局版本的操作符;而仅针对某个具体类别做特殊处理则更适合于局部范围内的操作符重写[^3]。 ```cpp // 定义一个简单的类 class MyClass { public: static void* operator new(size_t size) { // 实现自己的内存分配逻辑, 这里只是简单调用了 ::operator new return ::operator new(size); } static void operator delete(void* ptr) noexcept { // 对应上面的新建运算符, 提供删除操作 ::operator delete(ptr); } }; ``` #### 利用 STL 分配器模式 除了直接干预 `new/delete` 行为外,还可以通过继承并特化标准库中的 `std::allocator` 或者其他类似的模板来构建适用于特定场景下的资源管理者。这种方法特别适合那些基于容器的数据结构,因为它们往往依赖于某种形式的动态存储管理策略[^2]。 下面的例子展示了如何创建一个用于栈上分配的小型向量: ```cpp #include <iostream> #include <vector> template<typename T> struct StackAllocator : public std::allocator<T> { private: char buffer_[1024]; // 假设我们有一个固定大小的缓冲区作为栈空间 char* current_; // 当前可用的位置指针 public: using value_type = T; template<class U> struct rebind { typedef StackAllocator<U> other; }; StackAllocator() noexcept : current_(buffer_) {} pointer allocate(size_type n, const void *hint=0){ if (n > sizeof(buffer_)) throw std::bad_alloc(); auto result = reinterpret_cast<pointer>(current_); current_ += n * sizeof(T); return result; } void deallocate(pointer p, size_type n){ /* 不需要实际释放 */ } }; int main(){ try{ std::vector<int, StackAllocator<int>> vec(5); for(int i = 0 ;i < 5;++i ) vec[i]=i*i; for(auto& v:vec) std::cout<<v<<" "; }catch(const std::exception&e){ std::cerr << e.what()<<'\n'; } } ``` 此代码片段实现了基本功能,但在生产环境中还需要更加健壮的设计以应对各种边界情况以及潜在的安全隐患。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值