迭代一个指向类的指针向量
Iterating through a vector of pointers to classes
所以我有一个问题,我试图得到一艘船的坐标并返回一个指针。然而,我得到一个问题,编译器没有检测到我为我的船类创建的私有变量。
在我的。h文件。
#ifndef BOARD_H
#define BOARD_H
#include "Ship.h"
#include<vector>
class Board
{
private:
std::vector<Ship *> shipList;
char score[10][10];
Ship *shipAt(int x, int y);
};
#endif
我的ship.h文件中的相关变量
private:
int x1,y1,x2,y2;
My function
Ship *Board::shipAt (int x, int y){
vector <Ship*> :: iterator locate; //locating the appropiate ship with this iterator
for ( locate = shipList.begin(); locate != shipList.end() ; locate++ ){
if( *locate.x1 == *locate.x2){
if(( y <= *locate.y1 && y >= *locate.y2) || (y <= *locate.y2 && y >= *locate.y1)){
return locate;
}
}
else if ( *locate.y1 == *locate.y2){
if(( x <= *locate.x1 && x >= *locate.x2) || ( x <= *locate.x2 && *locate.x1)){
return locate;
}
}
}
}
I'm getting the error
Board.cpp:54:15: error: ‘std::vector<Ship*>::iterator’ has no member named ‘x1’
if( *locate.x1 == *locate.x2){
^
Board.cpp:54:29: error: ‘std::vector<Ship*>::iterator’ has no member named ‘x2’
if( *locate.x1 == *locate.x2){
第一个问题是操作符优先级。你试图解引用locate.x1
,而实际上你想做的是先解引用locate
来获得指针,然后访问x1
成员。所以你想要的代码是(*locate).x1
(见下一段)
那么你还有两个问题。因为你有一个指针,因此要访问x1
,你需要使用->
,而不是' .
'。
最后你会遇到可见性问题,因为x1
是私有的。
错误信息给出了一个很好的诊断:
error: ' std::vector<Ship*>::iterator '没有名为' x2 '的成员
编译器告诉你iterator
类型没有成员x2
,这应该是一个提示,你试图从错误的对象类型访问x2
。您正在尝试从Ship
访问x2。
虽然frozenkoi的回答很好,但您可能对以下问题感兴趣。
- 不要使用指针。使用智能指针,例如http://www.boost.org/doc/libs/1_55_0/libs/smart_ptr/smart_ptr.htm
- 记住增量前和增量后的区别。总是在迭代器中使用预进/自减!
- 使用众所周知的算法来解决众所周知的和有充分记录的问题。在你的情况下点内矩形测试
更整洁,更容易阅读:
Ship* Board::shipAt (int x, int y)
{
for ( auto s : shipList )
{
if( x < min(s->x1,s->x2) ) continue;
if( x > max(s->x1,s->x2) ) continue;
if( y < min(s->y1,s->y2) ) continue;
if( y > max(s->y1,s->y2) ) continue;
return s;
}
return nullptr;
}
相关文章:
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 如何更改唯一指针向量的可见性
- 如何在基类指针向量的元素上应用重载的多态函数
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 包含指向其他结构的指针向量的结构
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 如何将字符串指针数组转换为字符串类型的智能指针向量?
- 初始化可变数据结构中的共享指针向量
- 指向具有 decltype 的函数的指针向量
- push_back指向指针向量的指针
- 使用指针向量(带代码)C++(以及对其使用的便利性的怀疑)时出现问题
- 我可以做些什么来改进指针向量中的此搜索?
- 指向指针排序向量的指针向量的 C++ 向量
- 初始化用户定义类的指针向量
- 函数无法识别我在C++传递节点指针向量?
- 如何声明指向类对象的指针向量?
- 指向结构的指针向量的元素具有相同的地址
- 删除指向抽象类的指针向量
- 当我返回指向结构的指针向量时出现段错误
- 用基于范围的for循环填充指针向量