C++/Set Multiset/set insert

Материал из C\C++ эксперт
Перейти к: навигация, поиск

set.insert returns pair: p.first represents location and p.second represents the successfulness

<source lang="cpp">

  1. include <iostream>

using std::cout; using std::endl;

  1. include <set>
  2. include <algorithm>
  3. include <iterator> // ostream_iterator

int main() {

  double a[ 5 ] = { 2.1, 4.2, 9.5, 2.1, 3.7 };
  std::set< double, std::less< double > > doubleSet( a, a + 5 );;
  std::ostream_iterator< double > output( cout, " " );
  // p represents pair containing const_iterator and bool
  std::pair< std::set< double, std::less< double > >::const_iterator, bool > p;
  p = doubleSet.insert( 13.8 ); // value not in set
  cout << *( p.first ) << ( p.second ? " was" : " was not" ) << " inserted";
  cout << "\ndoubleSet contains: ";
  std::copy( doubleSet.begin(), doubleSet.end(), output );
  cout << endl;
  return 0;

} /* 13.8 was inserted doubleSet contains: 2.1 3.7 4.2 9.5 13.8

*/        
 </source>