迭代一个指向类的指针向量

Iterating through a vector of pointers to classes

本文关键字:指针 向量 一个 迭代      更新时间:2023-10-16

所以我有一个问题,我试图得到一艘船的坐标并返回一个指针。然而,我得到一个问题,编译器没有检测到我为我的船类创建的私有变量。

在我的。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
  1. 记住增量前和增量后的区别。总是在迭代器中使用预进/自减!
  2. 使用众所周知的算法来解决众所周知的和有充分记录的问题。在你的情况下点内矩形测试

更整洁,更容易阅读:

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;
}