Saturday, October 17, 2015

c++ set

c++ set

Set is very useful data structure in C++.
It is like an array but it has lots of useful tools.
Tools that I often use and introduce are..

Format
std :: set < type > setName
    -> if you use "using namesapace std", you do not need std ::
    -> type can be int, char, string and vice versa

    .insert( "item" )
        - insert value in a set

    .size(   )
        - check number of item in a set

    .find( "item")
    .find( "index")
       - find item by using element or index.
       - This function is really powerful because it find element in O(1).
             -> every element is in hash. when it search for item, what it needs to is looking the hash value
       - if find cannot find it returns .end ()

    .erase( "item" )
    .erase( "index" )
        - erase element by using element or index

If you want to grab a element from set,  use iterator
ex) 
  set < string > :: iterator checker
  checker = yourSet.find("item")
  cout << *checker << endl;
------------------------------------------------------------------------------------------------------------------------------

The following is practice code. If you have suggestion or correction, please feel free to leave comment

#include <iostream>
#include <set>
using namespace std;

int main(int argc, char** argv) {
   
    set <string> aSet;
    set <string>::iterator checker;
    set <string>::iterator element;
   
    string input1 = "one";
    string input2 = "two";
    string input3 = "three";
    string input4 = "four";
    string inputDummy = "one";
   
    aSet.insert( input1 );
    aSet.insert( input2 );
    aSet.insert( input3 );
    aSet.insert( input4 );
    aSet.insert( inputDummy );
   
    // 1
    //return three because input1 and inputDummy have same value
    cout << aSet.size() << endl;
   
    //2
    //return one because set has one
    checker = aSet.find("one");
    if( checker != aSet.end() )
        cout << "one" << endl;
   
    //3
    //return none because has one
    checker = aSet.find("five");
    if( checker == aSet.end() )
        cout << "five is not in the set" << endl << endl;
   
    //4
    //print every elements
    //print in alphabetical order
    for( element = aSet.begin(); element != aSet.end() ; element++ ){
        cout << *element << endl;
    }
   
    //5
    //erase element of set by value and index
    aSet.erase( "one" );
    aSet.erase( input2 );
    cout << endl;
   
    //6
    //print every elements
    for( element = aSet.begin(); element != aSet.end() ; element++ ){
        cout << *element << endl;
    }
   
   
    return 0;
}



No comments:

Post a Comment