我有一个矢量:
vector<Player> players;
players.push_back(Player(20000));
players.push_back(Player(10000));
players.push_back(Player(12000));
players.push_back(Player(32000));
players.push_back(Player(22000));
players.push_back(Player(18000));
我像这样循环:
for (Player &player : players)
std::cout << player._gold << endl;
有没有办法命名起始索引并通过玩家完整循环? 像
//pseudo
for (Player &player : players, 2)
std::cout << player._gold << endl;
会给出
12000
32000
22000
18000
20000
10000
请注意,它从第3个元素(索引2)开始,并且它不会在向量的末尾停止。请给我一些关键词或示例如何用c ++中最简单的方式来做。
答案 0 :(得分:-1)
您需要创建一个适配器对象,例如
template<class T>
class iterator_range
{
private:
typename T::iterator begin_;
typename T::iterator end_;
public:
iterator_range(typename T::iterator b, typename T::iterator e):begin_(b),end_(e)
{
}
typename T::iterator begin() const
{
return begin_;
}
typename T::iterator end() const
{
return end_;
}
};
您现在可以
for (Player &player : iterator_range(players.begin()+2,players.end()))
std::cout << player._gold << endl;