Receipt of a new vector element c++



  • As I understand it, when the element is added to the vector through emplace_back, it will be free (i.e., the element was removed, this is the free spot) or at the end of the vector. Question: How do you get an index to the newly added vector element?



  • If you're interested in the index to the added element, not the terator, then you can get it, let's say:

    #include <iostream>
    #include <vector>
    #include <utility>
    

    int main()
    {
    std::vector<std::pair<int, char>> v;

    v.emplace_back( int( 'A' ), 'A' );
    
    auto p = &amp;v.back();
    
    std::cout &lt;&lt; p-&gt;first &lt;&lt; ": " &lt;&lt; p-&gt;second &lt;&lt; std::endl;
    

    }

    Programme withdrawal:

    65: A

    If you use the method insert instead of one of the injection techniques at the end of the vector, method insert returns the terator to the emplacement. So you can get an index to the element using this terator. For example,

    #include <iostream>
    #include <vector>
    #include <algorithm>

    int main()
    {
    std::vector<int> v = { 1, 2, 4, 5 };

    auto it = v.insert( std::find( v.begin(), v.end(), 4 ), 3 );
    
    int *p = &amp;*it;
    
    std::cout &lt;&lt; *it &lt;&lt; "\t" &lt;&lt; *p &lt;&lt; std::endl;
    

    }

    Programme withdrawal:

    3   3

    Both the terator and the index shall be used in the programme for handling the component.

    Also as you can turn to the vector elements using the indexing operator, you can always get an index to any element knowing its index.

    std::vector<int> v = { 1, 2, 3, 4, 5 };

    int *p = &v[2];

    In view of the fact that when the vector element is removed, all the elements behind the removed element shall be moved to the beginning of the vector, taking up the remote element, unless the remote element was the last part of the vector.
    So the elements of the vector are always located consecutively behind each other at a continuous memory site. There's no dirt in the vector.

    If you need to put elements in the middle of the vector, you'd better use it. std::dequeor if there is no need for direct access to the elements, std::list


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2