我需要将一个对象插入到现有的对象 vector 中。我知道我需要使用迭代器来完成它,但我不知道它究竟是如何工作的。
我有按字母顺序排序的 vector ,我需要在搜索后得到的确切索引中按名称插入新对象。所以我有这个。
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
任何人都可以帮助我如何正确使用迭代器将我的对象插入 vector 的第 54 个索引并将所有后续对象移动一个索引?
感谢您的帮助。
最佳答案
直接的答案是您需要一个迭代器。 std::vector 的迭代器支持随机访问,这意味着您可以在迭代器中添加或减去整数值。
people.insert(people.begin() + index, temp);
更好的答案是不要使用索引,使用迭代器。你的循环是什么?您应该能够重构循环以使用迭代器而不是索引。
关于c++ - 在 vector C++ 的索引处插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22432243/