在向量C ++的索引处插入对象 [英] Insert object at index of vector c++

查看:47
本文介绍了在向量C ++的索引处插入对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个对象插入到对象的现有向量中.我知道我需要使用迭代器来做到这一点,但我不知道它是如何工作的.

I need to insert an object to existing vector of objects. I know that i need to use iterator to do it but i dont know how it exactly works.

我有按字母顺序排序的向量,我需要按名称将新对象插入经过一些搜索后得到的确切索引中.所以我有这个.

I have alphabetically sorted vector and i need to insert new object by its name in exact index that i got after some search . So i have this.

vector<Person>people;


int index =54;
Person temp;

people.push_back(temp);//insert at end of vector
people.insert(index, temp);//doesnt work for int

有人可以帮助我如何正确使用迭代器将对象插入向量的第54个索引并将所有后续对象移动一个索引吗?

Can anyone help me how to use iterator properly to insert my object to 54th index of vector and move all following object by one index ?

谢谢您的帮助.

推荐答案

直接的答案是您需要一个迭代器.std :: vector的迭代器支持随机访问,这意味着您可以在迭代器中添加或减去一个整数值.

The straight forward answer is you need an iterator. The iterator for std::vector supports random access, which means you can add or subtract an integer value to or from an iterator.

people.insert(people.begin() + index, temp);

更好的答案是不要使用索引,而要使用迭代器.你的循环是什么?您应该能够重构循环,以使用迭代器而不是索引.

The better answer is don't use an index, use an iterator. What is your loop? You should be able to refactor the loop to use an iterator instead of an index.

这篇关于在向量C ++的索引处插入对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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