按值删除向量中的元素 [英] Deleting an element in a vector by value

查看:81
本文介绍了按值删除向量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的新手,我的问题是如何从Flight中检索一个对象与主要的输入(flightNumber)进行比较?如何在main中声明属性类型?错误消息显示第二行最后一行'int'无效转换为'Flight'。



I'm new to C++ and my question is how can I retrieve an object from the Flight to be compared to the input (flightNumber) in the main? How do I declare the attributes type in the main? The error message displays "invalid conversion of 'int' to 'Flight' in the second last line.

class Flight{
int FlightNumber 
};
class TravelAgent
{
    vector <flight> flightList;
};
void Agent::delete(Flight *obj)
{
    vector<flight*>::iterator ptr;
    for(ptr=flightList.begin();ptr!=flightList.end();ptr++)
    {
        if((*Ptr)==obj)
        {
            flightList.erase(ptr);
            break;
        }
    }
    if ((ptr) == flightList.end())
    {
        cout<<"Flight not found"<<endl;
    }
}
int main{
      Agent agent1;
      int flightNumber;
      cout<<"Enter the number of the flight: "<<flush;
      in>>flightNumber;
      agent1.delete(flightNumber); 
}

推荐答案

尝试:

Try:
void Agent::delete(int flightNumber)
{
    vector<flight*>::iterator ptr;
    for(ptr=flightList.begin();ptr!=flightList.end();ptr++)
    {
        if( ptr->FlightNumber == flightNumber)
        {
           flightList.erase(ptr);
           return;
        }
    }
    if ((ptr) == flightList.end())
    {
        cout<<"Flight not found"<<endl;
    }
}





请注意, std :: vector 可能不是这项工作的最佳容器(参见 http://www.cplusplus.com / reference / vector / vector / erase / [ ^ ]详情)。



Please note, a std::vector is possibly NOT the best container for such a job (see http://www.cplusplus.com/reference/vector/vector/erase/[^] for details).


这篇关于按值删除向量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆