std::deque:如何获得指向指定索引处的元素的迭代器?
我有一个 std::deque,我想在指定的索引处插入一个元素(我知道 std::list 会更好)。 deque::insert() 函数采用迭代器来指定要插入的位置。给定一个索引,如何获得指向该位置的迭代器,以便我可以将该迭代器传递给 insert() ?
例如:
void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
deque<Thing>::iterator it = /* what do I do here? */
things.insert ( it, thing );
}
我确信这是一个非常基本的问题,对此我表示歉意。我已经很久没有使用STL了,而且我在std::deque的成员列表中没有看到任何明显能满足我要求的东西。谢谢。
I have a std::deque, and I want to insert an element at a specified index (I'm aware that std::list would be better at this). The deque::insert() function takes an iterator to specify the location to insert. Given an index, how can I get an iterator pointing to that location, so that I can pass that iterator to insert()?
For example:
void insertThing ( deque<Thing> & things, Thing thing, size_t index )
{
deque<Thing>::iterator it = /* what do I do here? */
things.insert ( it, thing );
}
I'm sure this is a very basic question, and I apologize for it. It's been a long time since I've used the STL, and I don't see anything in std::deque's member list that obviously does what I want. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
双端队列支持随机访问,所以你应该可以说
A deque supports random access, so you should be able to say
我喜欢代码中没有警告的干净解决方案,因此 std::deque::iterator operator+ 为有符号整数代码重载,例如:
引入警告。
所以我更喜欢更好的解决方案:
I like clean soulution without warnings in code, so as std::deque::iterator operator+ overloaded for signed integer code like:
Introduce warning.
So better solution I like more: