Insert object at index of vector c++

前端 未结 3 487
面向向阳花
面向向阳花 2021-01-07 10:11

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 sor

相关标签:
3条回答
  • 2021-01-07 10:56

    Solution:

        vector<Person>::iterator iter = people.begin() + index;
        people.insert(iter, temp);
    

    Reference:

    • std::vector::insert()

    • RandomAccessIterator

    0 讨论(0)
  • 2021-01-07 10:59

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

    If the vector is sorted alphabetically, then the proper way of inserting an item in the correct position while maintaining the sort order is using the upper_bound function:

    people.insert(upper_bound(people.begin(), people.end(), temp), temp);
    

    The function searches the sorted range, and returns the position of the first element that is greater than temp.

    Here is a demo on ideone.

    0 讨论(0)
  • 2021-01-07 11:03

    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.

    0 讨论(0)
提交回复
热议问题