我不知道如何在模板 c++ 中指定运算符

问题描述 投票:0回答:1
struct Info1 {
    int l;
    int r;
};

我想制作 2 个对象 Info1 但使用不同的运算符< , i dont want to write two structs and two bool operator< for each one , instead write a template with the min function specified in the main.

所以例如我有一个像下面这样的线段树类

class SegmentTree {
    vector<int> tree;
    int size;
 
public:
    SegmentTree(vector<int>& array) {
        size = array.size();
        tree.resize(4 * size);
        buildTree(array, 0, 0, size - 1);
    }
 
private:
    void buildTree(vector<int>& array, int treeIndex, int left, int right) {
        if (left == right) {
            tree[treeIndex] = array[left];
            return;
        }
        int mid = left + (right - left) / 2;
        buildTree(array, 2 * treeIndex + 1, left, mid);
        buildTree(array, 2 * treeIndex + 2, mid + 1, right);
        tree[treeIndex] = min(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
    }
 
    int query(int treeIndex, int left, int right, int queryLeft, int queryRight) {
        if (queryLeft <= left && right <= queryRight)
            return tree[treeIndex];
        int mid = left + (right - left) / 2;
        int minValue = INT_MAX;
        if (queryLeft <= mid)
            minValue = min(minValue, query(2 * treeIndex + 1, left, mid, queryLeft, queryRight));
        if (queryRight > mid)
            minValue = min(minValue, query(2 * treeIndex + 2, mid + 1, right, queryLeft, queryRight));
        return minValue;
    }
 
public:
    int query(int left, int right) {
        return query(0, 0, size - 1, left, right);
    }
};

我想制作两棵 seg 树的一棵最大树和一棵最小树……有没有办法制作一个模板并将最小函数传递给该模板,以便对最小和最大树使用相同的类?

c++ class templates struct operators
1个回答
0
投票

你不需要模板,你只需要两个不同的比较器。例如

struct LeftLessThan
{
    bool operator()(Info1 x, Info2 y) const { return x.l < y.l; }
};

struct RightLessThan
{
    bool operator()(Info1 x, Info2 y) const { return x.r < y.r; }
};

然后你可以像这样使用它们

std::sort(info.begin(), info.end(), LeftLessThan()); // sort on left
std::sort(info.begin(), info.end(), RightLessThan()); // sort on right
© www.soinside.com 2019 - 2024. All rights reserved.