如何使用另一个变量访问对象的变量/方法

时间:2016-02-16 20:24:18

标签: c++ class oop struct

假设我有struct Node,其中包含xy,我想创建这些Node的向量。

struct Node {
    int x;
    int y;
    Node(int x, int y);
};

vector<Node *> nodes;

我想编写可在xy上运行的各种功能。例如,我想编写一个sort函数,按x坐标对节点向量进行排序,另一个根据y进行排序。

编写实现sort_by_x和sort_by_y的单个函数绝对是一个更好的主意。我正在考虑编写一个函数,它接受bool isX,并相应地执行排序。但是,我想避免两次写相同的代码(一次为x,一次为y)。我想编写一段执行相应排序的代码。我尝试使用以下代码实现它,但它在C ++中无效(因为它期望c成为Node中的变量之一)。

void mySort(vector<Node *> &nodes, bool isX) {
    char c;
    if (isX) {
        c = 'x';
    }
    else {
        c = 'y';
    }

    // some code
    nodes[i]->c // if c == 'x', x will be used, otherwise  y.
}

请您让我一个解决方法来重写上面的代码或基于不同变量实现相同功能的其他方法吗?

3 个答案:

答案 0 :(得分:4)

您可以在此处使用指向成员的指针:

int Node::*m;
if (isX) {
    m = &Node::x;
}
else {
    m = &Node::y;
}

// some code
nodes[i]->*m

语法相当丑陋,但它完全符合您的要求。如果你有C ++ 11可用,另一种方法是编写简单的lambda函数来返回xy并将它们存储在std::function中;这效率略低,但不那么丑陋,也不那么普遍。

答案 1 :(得分:3)

std::sort允许比较器作为第三个参数传入。您可以通过为x案例和y案例使用不同的比较器来更改排序行为。

std::sort(nodes.begin(), nodes.end(),
          [](const Node *a, const Node *b) -> bool {
              return a->x < b->x;
          });

答案 2 :(得分:1)

您不必编写自己的函数来进行排序。标准库已具有通用sort功能。您可以像这样使用它:

auto x_comparator = [](auto a, auto b) { return a->x < b->x; }
auto y_comparator = [](auto a, auto b) { return a->y < b->y; }

std::sort(nodes.begin(), nodes.end(), x_comparator); // sort by x
std::sort(nodes.begin(), nodes.end(), y_comparator); // sort by y