Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::map<Key,T,Compare,Allocator>::insert

      From cppreference.com
      <cpp‎ |container‎ |map
       
       
       
      std::map
      Member functions
      Non-member functions
      (until C++20)(until C++20)(until C++20)(until C++20)(until C++20)
      Deduction guides(C++17)
       
      std::pair<iterator,bool> insert(const value_type& value);
      (1)
      template<class P>
      std::pair<iterator,bool> insert( P&& value);
      (2)(since C++11)
      std::pair<iterator,bool> insert( value_type&& value);
      (3)(since C++17)
      (4)
      iterator insert( iterator pos,const value_type& value);
      (until C++11)
      iterator insert( const_iterator pos,const value_type& value);
      (since C++11)
      template<class P>
      iterator insert( const_iterator pos, P&& value);
      (5)(since C++11)
      iterator insert( const_iterator pos, value_type&& value);
      (6)(since C++17)
      template<class InputIt>
      void insert( InputIt first, InputIt last);
      (7)
      void insert(std::initializer_list<value_type> ilist);
      (8)(since C++11)
      insert_return_type insert( node_type&& nh);
      (9)(since C++17)
      iterator insert( const_iterator pos, node_type&& nh);
      (10)(since C++17)

      Inserts element(s) into the container, if the container doesn't already contain an element with an equivalent key.

      1-3) Insertsvalue.
      Overload(2) is equivalent toemplace(std::forward<P>(value)) and only participates in overload resolution ifstd::is_constructible<value_type, P&&>::value==true.
      4-6) Insertsvalue in the position as close as possible to the position just prior topos.
      Overload(5) is equivalent toemplace_hint(pos,std::forward<P>(value)) and only participates in overload resolution ifstd::is_constructible<value_type, P&&>::value==true.
      7) Inserts elements from range[firstlast). If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pendingLWG2844).
      8) Inserts elements from initializer listilist. If multiple elements in the range have keys that compare equivalent, it is unspecified which element is inserted (pendingLWG2844).
      9) Ifnh is an emptynode handle, does nothing. Otherwise, inserts the element owned bynh into the container , if the container doesn't already contain an element with a key equivalent tonh.key(). The behavior is undefined ifnh is not empty andget_allocator()!= nh.get_allocator().
      10) Ifnh is an emptynode handle, does nothing and returns the end iterator. Otherwise, inserts the element owned bynh into the container, if the container doesn't already contain an element with a key equivalent tonh.key(), and returns the iterator pointing to the element with key equivalent tonh.key()(regardless of whether the insert succeeded or failed). If the insertion succeeds,nh is moved from, otherwise it retains ownership of the element. The element is inserted as close as possible to the position just prior topos. The behavior is undefined ifnh is not empty andget_allocator()!= nh.get_allocator().

      No iterators or references are invalidated.If the insertion is successful, pointers and references to the element obtained while it is held in the node handle are invalidated, and pointers and references obtained to that element before it was extracted become valid.(since C++17)

      Contents

      [edit]Parameters

      pos - iterator to the position before which the new element will be inserted
      value - element value to insert
      first, last - the pair of iterators defining therange of elements to insert
      ilist - initializer list to insert the values from
      nh - a compatiblenode handle
      Type requirements
      -
      InputIt must meet the requirements ofLegacyInputIterator.

      [edit]Return value

      1-3) A pair consisting of an iterator to the inserted element (or to the element that prevented the insertion) and abool value set totrue if and only if the insertion took place.
      4-6) An iterator to the inserted element, or to the element that prevented the insertion.
      7,8) (none)
      9) An object ofinsert_return_type with the members initialized as follows:
      • Ifnh is empty,inserted isfalse,position isend(), andnode is empty.
      • Otherwise if the insertion took place,inserted istrue,position points to the inserted element, andnode is empty.
      • If the insertion failed,inserted isfalse,node has the previous value ofnh, andposition points to an element with a key equivalent tonh.key().
      10) End iterator ifnh was empty, iterator pointing to the inserted element if insertion took place, and iterator pointing to an element with a key equivalent tonh.key() if it failed.

      [edit]Exceptions

      1-6) If an exception is thrown by any operation, the insertion has no effect.
      This section is incomplete
      Reason: cases 7-10

      [edit]Complexity

      1-3) Logarithmic in the size of the container,O(log(size())).
      4-6) Amortized constant if the insertion happens in the position justafter(until C++11)before(since C++11)pos, logarithmic in the size of the container otherwise.
      7,8)O(N·log(size() + N)), whereN is the number of elements to insert.
      9) Logarithmic in the size of the container,O(log(size())).
      10) Amortized constant if the insertion happens in the position justbeforepos, logarithmic in the size of the container otherwise.

      [edit]Notes

      The hinted insert((4-6) and(10))does not return a boolean in order to be signature-compatible with positional insert on sequential containers, such asstd::vector::insert. This makes it possible to create generic inserters such asstd::inserter. One way to check success of a hinted insert is to comparesize() before and after.

      [edit]Example

      Run this code
      #include <iomanip>#include <iostream>#include <map>#include <string>usingnamespace std::literals; template<typename It>void print_insertion_status(It it,bool success){std::cout<<"Insertion of "<< it->first<<(success?" succeeded\n":" failed\n");} int main(){std::map<std::string,float> heights; // Overload 3: insert from rvalue referenceconstauto[it_hinata, success]= heights.insert({"Hinata"s,162.8});    print_insertion_status(it_hinata, success); {// Overload 1: insert from lvalue referenceconstauto[it, success2]= heights.insert(*it_hinata);        print_insertion_status(it, success2);}{// Overload 2: insert via forwarding to emplaceconstauto[it, success]= heights.insert(std::pair{"Kageyama",180.6});        print_insertion_status(it, success);}{// Overload 6: insert from rvalue reference with positional hintconststd::size_t n=std::size(heights);constauto it= heights.insert(it_hinata,{"Azumane"s,184.7});        print_insertion_status(it,std::size(heights)!= n);}{// Overload 4: insert from lvalue reference with positional hintconststd::size_t n=std::size(heights);constauto it= heights.insert(it_hinata,*it_hinata);        print_insertion_status(it,std::size(heights)!= n);}{// Overload 5: insert via forwarding to emplace with positional hintconststd::size_t n=std::size(heights);constauto it= heights.insert(it_hinata,std::pair{"Tsukishima",188.3});        print_insertion_status(it,std::size(heights)!= n);} auto node_hinata= heights.extract(it_hinata);std::map<std::string,float> heights2; // Overload 7: insert from iterator range    heights2.insert(std::begin(heights),std::end(heights)); // Overload 8: insert from initializer_list    heights2.insert({{"Kozume"s,169.2},{"Kuroo",187.7}}); // Overload 9: insert nodeconstauto status= heights2.insert(std::move(node_hinata));    print_insertion_status(status.position, status.inserted);     node_hinata= heights2.extract(status.position);{// Overload 10: insert node with positional hintconststd::size_t n=std::size(heights2);constauto it= heights2.insert(std::begin(heights2), std::move(node_hinata));        print_insertion_status(it,std::size(heights2)!= n);} // Print resulting mapstd::cout<<std::left<<'\n';for(constauto&[name, height]: heights2)std::cout<<std::setw(10)<< name<<" | "<< height<<"cm\n";}

      Output:

      Insertion of Hinata succeededInsertion of Hinata failedInsertion of Kageyama succeededInsertion of Azumane succeededInsertion of Hinata failedInsertion of Tsukishima succeededInsertion of Hinata succeededInsertion of Hinata succeeded Azumane    | 184.7cmHinata     | 162.8cmKageyama   | 180.6cmKozume     | 169.2cmKuroo      | 187.7cmTsukishima | 188.3cm

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 233C++98pos was just a hint, it could be totally ignoredthe insertion is required to
      be as close as possible to the
      position just prior topos
      LWG 264C++98the complexity of overload(7) was required to be linear if
      the range[firstlast) is sorted according toCompare
      removed the linear requirement
      in this special case
      LWG 316C++98in the return value of overload(1), it was not specified
      whichbool value indicates a successful insertion
      success is
      indicated bytrue
      LWG 2005C++11overloads(2) and(5) were poorly describedimproved the description

      [edit]See also

      (C++11)
      constructs element in-place
      (public member function)[edit]
      constructs elements in-place using a hint
      (public member function)[edit]
      inserts an element or assigns to the current element if the key already exists
      (public member function)[edit]
      creates astd::insert_iterator of type inferred from the argument
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/container/map/insert&oldid=183129"

      [8]ページ先頭

      ©2009-2025 Movatter.jp