访问std :: pair数组的元素时出错

时间:2011-09-30 18:43:10

标签: c++ arrays stl std-pair

我已经定义了一对数组,如下所示:

std::pair<int,int> delta[4];
delta[0] = std::make_pair(0,1);
delta[1] = std::make_pair(1,1);
delta[2] = std::make_pair(1,0);
delta[3] = std::make_pair(1,-1);

但是当我尝试访问像:

这样的元素时
delta[2].first

我收到如下错误:

binary '[' : 'std::pair<_Ty1,_Ty2>' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2228: left of '.first' must have class/struct/union

以下是我访问它的功能:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>

int who_won(std::pair<int,int> &delta,std::vector<std::vector<int>> &grid);

int main(int argc, char** argv)
{
    std::fstream input;
    input.open("E:\\in.txt",std::ios_base::in);
    std::string line;
    char ch;
    std::vector<std::vector<int>> grid;
    std::vector<int> row;
    while(input.get(ch))
    {
        if(ch == '\n')
        {
            grid.push_back(row);
            row.clear();
        }
        else if(ch != ',')
        {
            row.push_back(std::atoi(&ch));
        }
    }

    if(row.size()>0)
        grid.push_back(row);
    row.clear();

    std::pair<int,int> delta[4];
    delta[0] = std::make_pair(0,1);
    delta[1] = std::make_pair(1,1);
    delta[2] = std::make_pair(1,0);
    int l = grid.size();
    for( int i =0; i < l; ++i)
    {
        //auto & v = *i;
        for( int j = 0; j < l; ++j)
            std::cout<<grid[i][j]<<" ";
        std::cout<<"\n";
    }

    int winner = who_won(*delta,grid);
    if( winner == 0)
    {
        if( std::find(grid.front().begin(),grid.front().end(),0) == grid.front().end())
            std::cout<<"draw";
        else
            std::cout<<"play";
    }
    else if( winner == 1)
        std::cout<<"1";
    else if( winner == 2)
        std::cout<<"2";


    return 0;
}

int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)
{
    int l = grid.size(),connect;
    for(int px = 0; px < l; ++px)
    {
        for(int py = 0; py < l; ++py)
        {

            for(int i = 0;i < 4;++i)
            {
                connect = 0;
                for(int j = 1;j < 4;++j)
                {
                    if( grid[px + delta[i].first*j][py + delta[i].second*j] != grid[px][py])
                        break;
                    else
                        connect++;
                }
                if(connect == 4)
                    return grid[px][py];
            }
        }
    }
    return -1;
}

我哪里错了?

1 个答案:

答案 0 :(得分:7)

您的方法签名仅指定对单个std::pair实例的引用。如果要传递std::pair数组,您可能希望您的签名看起来像以下内容。

int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)