在向量C ++的索引处插入对象

Pas*_*stx 1 c++ 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
Run Code Online (Sandbox Code Playgroud)

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

感谢您的任何帮助。

Jef*_*mas 8

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

people.insert(people.begin() + index, temp);
Run Code Online (Sandbox Code Playgroud)

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