如何访问向量内数据结构内的变量。我正在使用 SDL 1.2
我正在制作一个向量列表,其中包含一个名为 SDL_Rect 的数据结构
SDL_Rect 里面有 4 个变量,如下所示:
typedef struct{
Sint16 x, y;
Uint16 w, h;
} SDL_Rect;
我想将“x”变量打印到命令提示符窗口。我不确定我做错了什么?
vector< vector<SDL_Rect> > hitBoxArray;
我在一个向量里面有一个向量,里面有一个数据结构。我不确定在下面编写我的代码时这是否会有所不同。
void (randomFunction)
{
int width = 10;
for (int i = 0; i < width; i++)
{
hitBoxArray.push_back(vector<SDL_Rect>());
cout<<hitBoxArray[1].x <---- this is the bit i cannot get to work
}
}
如果您想知道为什么我在向量中有一个向量,这是因为此代码用于创建平铺地图,第一个向量用于行,第二个向量用于列,并且该代码工作正常。只有当我试图访问导致我出现问题的数据结构中的各个变量时。
下面是我的工作代码,如果有帮助,还包括注释中的非工作代码。
类内函数代码:tileDriver.cpp
void tile::readMapFile(string filename)
{
fstream map;
map.open(filename);
if(map.is_open())
{
map>>width;
map>>height;
cout<<"The width of the tile map is "<<width<<endl;
cout<<"The height of the tile map is "<<height<<endl<<endl;
for (int i = 0; i < width; i++)
{
tiles.push_back(vector<int>()); // Add an empty row for tile sprites
hitBoxArray.push_back(vector<SDL_Rect>()); // Add an empty row for hit boxes
//this bit is the code that will not work for me
cout<<hitBoxArray[1].x;
//this bit is the code that will not work for me
}
for (int j = 0; j < height; j++)
{
for (int i = 0; i < tiles.size(); i++)
{
tiles[i].push_back(i * j); // Add column to all rows for tile
sprites
map>>tiles[i][j];
}
for (int i = 0; i < hitBoxArray.size(); i++)
{
hitBoxArray[i].push_back(hitBox); // Add column to all rows for tile hit boxes
}
}
}
else
{
cout<<"unable to load map for tiled textures! did you spell the name correctly?";
}
}
头文件:tileHeader.h
#include<iostream>
#include<fstream>
#include<vector>
#include "SDL.h"
using namespace std;
class tile
{
protected:
SDL_Surface* ground;
SDL_Surface* grass;
SDL_Rect groundTile;
SDL_Rect grassTile;
SDL_Rect hitBox;
SDL_Rect* temp;
vector< vector<SDL_Rect> > hitBoxArray;
int width;
int height;
vector< vector<int> > tiles;
public:
tile();
void readMapFile(std::string filename);
void printMap();
void show(SDL_Surface* scr);
void show(SDL_Surface* scr, SDL_Rect cam);
SDL_Rect getHitBox();
vector< vector<SDL_Rect> > getHitBoxArray();
};
这是我在编译器中遇到的错误:
错误 1 错误 C2039: 'x' : is not a member of 'std::vector<_Ty>' C:\Users\vishal\Desktop\game\game\tileDriver.cpp 52
我正在使用 Visual Studio 2010 作为我的编译器
任何帮助、煽动或参考教程以帮助我解决我的问题将不胜感激:)