如何将向量作为可变参数传递给向量?

时间:2017-07-23 09:47:44

标签: c++

class Hex
{
    short type; 
    Hex(short typE)
    {
        type = typE;
    }
}
vector< vector<Hex> > hexes;

void HexRings(sf::Vector2i pos, void operation(sf::Vector2i, va_list), ...)
{
    va_list args;
    va_start(args, operation);
    //block of irrelevant changes of pos
    operation(pos, args);
    //another block of irrelevant changes of pos
    va_end(args);
}
void MakeHexTypeX(sf::Vector2i pos, va_list args)
{
    hexes[pos.x][pos.y].type = va_arg(args, int);
}
void AddHexes(sf::Vector2i pos, va_list args)
{
    vector<sf::Vector2i> returnThat;
    returnThat = va_arg(args, vector<sf::Vector2i>());// how to make this line actually give back a reference to the original vector (visited)
    list.push_back(sf::Vector2i(pos.x, pos.y));
}

int main()
 {
     vector<sf::Vector2i> visited;
    for(int y=0; y<10; ++y)
      {
          hexes.push_back(vector<Hex>());
          for(int x=0; x<10; ++x) hexes[x].push_back(Hex(0));
      }

    HexRings(sf::Vector2i(5, 5), AddHexesOfTypeX, visited);
    HexRings(sf::Vector2i(5, 5), MakeHexTypeX, 1);
 }

我有一个函数(HexRings),它在二维向量上以特定模式迭代。我希望能够将指向另一个函数(如MakeHexTypeX或AddHexes)的指针传递给此函数,该函数对每个访问过的磁贴执行特定操作。一切都很好,如果这个功能正在改变地图,但我不知道该怎么做,如果这个功能必须报告回来。例如,如果我想获得X型的所有六边形,那就是HexRings遇到的,那么矢量必须作为参考传递,我甚至不知道如何写。

TL; DR :如何将对矢量的引用作为可变参数传递?

1 个答案:

答案 0 :(得分:1)

我不会将操作函数传递给HexRings,而是将引用传递给函子。 Functors可以存储状态,从而保存您想要的矢量。我们走了:

struct processor {

    // you will be overriding this for every different operation you want to perform
    virtual void operator()(sf::Vector2i, va_list) = 0;
};

struct make_hex_type_x
: public processor {

    void operator()(sf::Vector2i pos, va_list args) override {
        hexes[pos.x][pos.y].type = va_arg(args, int);
    }
};

struct add_hexes
: public processor {

private:
    // this is our state
    vector<sf::Vector2i> returnThat;

public:

    void operator()(sf::Vector2i pos, va_list args) override {
        returnThat = va_arg(args, vector<sf::Vector2i>());
        list.push_back(sf::Vector2i(pos.x, pos.y));
    }

    // get access to your return vector
    vector<sf::Vector2i>& get() {
        return returnThat;
    }
};

//now change HexRings so that it accepts the functor instead of a function
void HexRings(sf::Vector2i pos, processor& pr, ...)
{
    va_list args;
    va_start(args, operation);
    //block of irrelevant changes of pos
    pr(pos, args);
    //another block of irrelevant changes of pos
    va_end(args);
}

// and finally call as follows
int main()
{
    vector<sf::Vector2i> visited;
    for(int y=0; y<10; ++y)
    {
        hexes.push_back(vector<Hex>());
        for(int x=0; x<10; ++x) hexes[x].push_back(Hex(0));
    }

    make_hex_type_x p1;
    add_hexes p2;

    HexRings(sf::Vector2i(5, 5), p2, visited);
    HexRings(sf::Vector2i(5, 5), p1, 1);

    // now extract your vector
    auto& vec = p2.get();
}