C++/Set Multiset/multiset iterator
iterator that cannot be used to change element values in multiset
#include <iostream>
using std::cout;
using std::endl;
#include <set> // multiset class-template definition
#include <algorithm> // copy algorithm
#include <iterator> // ostream_iterator
int main()
{
int a[ 10 ] = { 7, 22, 9, 1, 18, 30, 100, 22, 85, 13 };
std::multiset< int, std::less< int > > intMultiset;
std::ostream_iterator< int > output( cout, " " );
intMultiset.insert( 15 );
intMultiset.insert( 15 );
// iterator that cannot be used to change element values
std::multiset< int, std::less< int > >::const_iterator result;
// find 15 in intMultiset; find returns iterator
result = intMultiset.find( 15 );
if ( result != intMultiset.end() ) // if iterator not at end
cout << "Found value 15\n"; // found search value 15
cout << endl;
return 0;
}
/*
Found value 15
*/
multiset<User Object>::const_iterator
#include <algorithm>
#include <functional>
#include <iostream>
#include <set>
#include <string>
#include <utility>
#include <vector>
using namespace std;
class Dog
{
public:
Dog( string name = "Unknown", string breed = "A",int year = 2000 );
bool operator<( const Dog& rhs ) const;
string breed() const;
string name() const;
void print() const;
int year() const;
private:
string breed_;
string name_;
int year_;
};
inline
Dog::Dog( string name, string breed, int year )
: breed_( breed ), name_( name ), year_( year )
{} // empty
inline
bool Dog::operator<( const Dog& rhs ) const
{ return name() < rhs.name(); }
inline
string Dog::breed() const
{ return breed_; }
inline
string Dog::name() const
{ return name_; }
inline
void Dog::print() const
{
cout << name() << ", a " << breed() << ", won in " << year()
<< endl;
}
inline
int Dog::year() const
{ return year_; }
bool equal_breed( const Dog winner, string breed );
int main( )
{
const char* breed[] = { "A","B", "C","D", "E" };
const char* name[] = { "a","b", "c","d", "e" };
const int year[] = { 1971, 1972, 1973, 1974, 1975 };
const int num_dogs = sizeof( breed ) / sizeof( breed[0] );
vector<Dog> v;
for( int i = 0; i < num_dogs; ++i )
v.push_back( Dog( name[i], breed[i], year[i] ) );
const Dog query( "A" );
cout << query.name();
set<Dog> winner_set( v.begin(), v.end() );
set<Dog>::const_iterator winner_set_end = winner_set.end();
// search in the set by value
set<Dog>::const_iterator spot = winner_set.find( query );
if( spot != winner_set_end )
spot->print();
else
cout << query.name() << " never won best-in-show\n";
const string query_breed( "A" );
for( spot = winner_set.begin(); spot != winner_set_end; ++spot )
if( spot->breed() == query_breed )
break;
}
inline
bool equal_breed( const Dog winner, string breed )
{ return winner.breed() == breed; }