如何声明对<int,int> :: first

-3 c++ stl vector

我想知道是否可以将一对[int,int]声明为宏。

所以我想知道我是否可以像

#define X pair<int,int>::first
#define Y pair<int,int>::second

int main()
{
    int a[10][10];
    pair<int,int> arr;
    int sum=0;
    ...
    for(auto p: arr)
        sum += a[Y][X] // a[p.second][p.first]
}
Run Code Online (Sandbox Code Playgroud)

但这是错误的。我可以声明一个可以这样表达的宏吗?

eer*_*ika 6

我想定义“ pair [int,int] :: first”,例如#define X pair [int,int] :: first

抵制你的诱惑。

/// Right
sum += a[p.Y][p.X];

/// Wrong
sum += a[Y][X] //but i want to do this
Run Code Online (Sandbox Code Playgroud)

好像您想这样做:

int Y = p.second;
int X = p.first;
Run Code Online (Sandbox Code Playgroud)

这样,您可以执行以下操作:

sum += a[Y][X];
Run Code Online (Sandbox Code Playgroud)

更好的是,似乎一门课程比一对更适合您:

struct Coordinates { // choose an appropriate name
    int x;
    int y;
};
Coordinates c {1, 2};
int Y = p.y;  // not necessary, but just to get the exact syntax you want
int X = p.x;
sum += a[Y][X];
Run Code Online (Sandbox Code Playgroud)