我需要访问deque“queArr”中特定位置的元素。从这个元素,它是类“plane”的对象,我需要调用成员函数getTime,它返回私有成员时间。问题是我不知道如何访问该元素,因为它可能在que中的任何位置。
我尝试过使用[]运算符和que.at()函数,两者都没有成功。这些是我在deque(https://en.cppreference.com/w/cpp/container/deque)定义中可以找到的唯一选项,这似乎是相关的。
这是当前的代码。它使用最低燃料(通过getFuel()访问)抓取元素的位置,然后使用添加到指向ques第一个元素的迭代器的位置通过.erease(pos)将其删除。在此之前,在注释的位置,我需要访问此元素的成员函数getTime并将其添加到变量totalArr。如何访问这是我目前的问题。
//namespace std is being used
landingDelay+=landingTime;
cout<<"A plane has started landing \n";
int quePos=0;
int ref=queArr.front().getFuel();
for(int j=0; j<queArr.size(); j++)
{
if(queArr.at(j).getFuel()<ref)
{
ref=queArr.at(j).getFuel();
quePos=j;
}
}
it=queArr.begin();
it+=quePos;
//I was thinking something here
queArr.erase(it);
任何帮助将非常感激 :)
如何使用STL函数std::min_element()
而不是手动滚动相同的功能:
const auto minFuel = min_element( begin( queArr ), end( queArr ),
[]( const auto& a, const auto& b) { return a.getFuel() < b.getFuel(); } );
if( minFuel != end( queArr ) )
{
cout << minFuel->getTime();
}
这是一个完整的工作示例:
#include <algorithm>
#include <iostream>
#include <deque>
using namespace std;
struct Plane
{
Plane( int fuel ) : _fuel{ fuel } {}
int getFuel() const { return _fuel; }
int getTime() const { return _fuel * 2; }
private:
int _fuel;
};
int main()
{
const auto queArr = deque<Plane>{ 1, 2, 3, 4, 5, -1, 10 };
const auto minFuel = min_element( begin( queArr ), end( queArr ),
[]( const auto& a, const auto& b) { return a.getFuel() < b.getFuel(); } );
if( minFuel != end( queArr ) )
{
cout << minFuel->getTime();
}
}
输出-2
。在Coliru上看到它。