访问std::pair数组元素时出错
error accessing elements of array of 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;
}
我哪里错了
您的方法签名只指定对单个std::pair
实例的引用。如果你想传递一个std::pair
数组,你可能希望你的签名看起来像下面这样。
int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)
相关文章:
- 数组元素打印的递归方法
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 为什么使用数组元素查找最大数字的程序不起作用?
- 数组元素更改值?
- 如何访问宏中定义的数组元素
- 将数组元素递增 1
- C++函数,它将数组、谓词和运算符作为参数,并将运算符应用于满足谓词的数组元素
- 存储指向动态数组元素的指针
- C++通过别名指针以静默方式将错误的类型分配给数组元素
- 在 std::map 中插入数组元素
- 使用指针访问数组元素时出现意外结果
- c++ 使用动态分配运算符反向数组元素
- 为什么在 c++ 中分配 char 数组元素时,分配的字符会被销毁?
- 缺少数组元素问题
- 如何在类中制作 2D 数组元素,然后在其构造函数中指定其维度?
- 创建一个函数来转换数组元素的类型并返回数组的地址
- 删除在结构 c++ 中声明的数组元素
- Getter 和 Setter 用于类 C++ 中的数组元素
- 将数组用作数组元素时出错
- 访问std::pair数组元素时出错