STL - set e multiset

Dal quarto capitolo di Designing Components with the C++ STL, di Ulrich Breymann. Parte dedicata ai container associativi ordinati.

Un set é una collezione di elementi distinti. Non ci possono dunque essere due elementi uguali in una collezione. Nella implementazione STL gli elementi sono ordinati anche se questo non sarebbe strettamente necessario, se non viene specificato un ordinatore, viene usato come default less<T>.

Un esempio d'uso di set:

#include<iostream>
#include<set>

using namespace std;

/**
* check the pair returned by an insert operation on set
*/
static void checkInsertResult(pair<set<int>::iterator, bool> res) {
cout << "Insertion ";
if(res.second == false)
cout << "not ";
cout << "performed";
if(res.second == true)
cout << " for " << *(res.first);
cout << endl;
}

int main() {
set<int> mySet;

// inserting 10 elements
for(int i = 0; i < 10; ++i)
checkInsertResult(mySet.insert(i));

// trying to insert an element twice does not succeed
checkInsertResult(mySet.insert(4));

// dump
set<int>::iterator it = mySet.begin();
for(it = mySet.begin(); it != mySet.end(); ++it)
cout << *it << ' ';
cout << endl;

// looking for an element that is not there
it = mySet.find(12);
if(it == mySet.end())
cout << "Can't find element 12 (as expected)" << endl;

// checking for an element in the set
if(mySet.count(4) == 1)
cout << "The element 4 is in the set" << endl;

// find and remove an element
it = mySet.find(4);
if(it != mySet.end()) {
mySet.erase(it);
cout << "The element 4 erased" << endl;
}

// erase an elment directly
if(mySet.erase(6) == 1)
cout << "The element 6 erased" << endl;
if(mySet.erase(6) == 0)
cout << "Can't erase element 6 (as expected)" << endl;

// dump
it = mySet.begin();
while(it != mySet.end())
cout << *it++ << ' ';
cout << endl;
}

Esiste anche la classe multiset, che permette l'esistenza di elementi ripetuti; l'interfaccia é praticamente identica a quella di set, con la differenza sostanziale del metodo insert() che ritorna, in caso di successo, l'iteratore che punta all'elemento inserito nel container.

Nessun commento:

Posta un commento