Showing posts with label STL. Show all posts
Showing posts with label STL. Show all posts

STLSet all operation example code in C++ Linux

Set is an associated template container. Only values are stored in set.Once value inserted can not be modified.If want to modify then first erase then modify. In map using at() or [] we can directly insert new value. Values are stored in sorted ascending order. Effect of inserting a duplicate value does nothing.
#include<iostream>
using namespace std;
#include<set>
#include<algorithm>
int main()
{
cout<<"Creating an empty set:"<<endl;
set<int> set;
cout<<"Inserting into a set"<<endl;
set.insert(11);
set.insert(33);
set.insert(22);
set.insert(55);
set.insert(44);//does nothing
set.insert(44);//does nothing
set.insert(44);//does nothing

cout<<"iTraversing through into a set"<<endl;
std::set<int>::iterator itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<"Searching in a set"<<endl;
itr=set.begin();
itr=set.find(55);
if(itr!=set.end())
cout<<"55 found"<<endl;
else
cout<<"55 not found"<<endl;

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"finding and deleting from a set"<<endl;
itr=set.begin();
itr=set.find(22);
if(itr!=set.end())
{
cout<<"22 found"<<endl;
set.erase(22);
//itr=set.erase(22);//change to other itr2
}
else
{
cout<<"22 not found"<<endl;
}

set.erase(22);//deleting again no effect
cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"Deleting a range"<<endl;
std::set<int>::iterator itr2=set.begin();
std::set<int>::iterator itr3=set.end();
set.erase(itr2,itr3);

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<""<<endl;
return 0;
}
/*
Creating an empty set:
Inserting into a set
iTraversing through into a set
11 22 33 44 55 Searching in a set
55 found
Traversing
11 22 33 44 55 finding and deleting from a set
22 found
Traversing
11 33 44 55 Deleting a range
Traversing

*/

C++ list example. All operations.

#include<iostream>
using namespace std;
#include<list>
#include<algorithm>

int main()
{
//creating an empty list
list<int> l;
//Way:1 to insert
l.push_back(10);
l.push_back(100);
l.push_back(20);
//Way:2 to insert

list<int>::iterator itr=l.begin();
while(itr!=l.end())
{
cout<<*itr<<"\t";
itr++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5
list<string> ls2(5);
list<string>::iterator itr2=ls2.begin();
while(itr2!=ls2.end())
{
cout<<*itr2<<"\t";
itr2++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5 with initial value "Mr"
list<string> ls3(5,"Mr");
list<string>::iterator itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

ls3.push_back("Mr");
ls3.push_back("Mr");
ls3.push_back("Mrs");
ls3.push_back("Miss");
ls3.push_back("Mrs");

cout<<"Way 0: to remove by value"<<endl;
ls3.remove("Mr");//deletes all a value "Mr"
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}


itr3=ls3.begin();
cout<<"Way 1: to erase single value by itr"<<endl;
list<string>::iterator itr4=ls3.begin();
itr3=ls3.erase(itr4);//1th element deleted
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<"\nWay 2: to erase range by iterator"<<endl;
itr3=ls3.begin();
list<string>::iterator itr5=ls3.begin();
list<string>::iterator itr6=ls3.end();
itr3=ls3.erase(itr5,itr6);//deletes begin to end
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

return 0;
}
/*
10      100     20     
Mr      Mr      Mr      Mr      Mr     
Way 0: to remove by value
Mrs     Miss    Mrs     Way 1: to erase single value by itr
Miss    Mrs    
Way 2: to erase range by iterator
*/

C++ STL interview questions

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?(except when erased member is first or last member of container)
Q) What is the difference between capacity and size in vector container in STL?
Q) If initially size allocated to vector is 10. What would be the capacity of the vector? Will it be doubled?
Q) Write a program to demonstrate vector's algorithms ?
Q) Write a program to demonstrate map and multi map's algorithms?
Q) Write a program to demonstrate set and multi set's operations ?
Q) What is the return type of find algorithm in STL container?
Q) Write a program to find the  first match of pattern in given strings and its position? Use vector of strings?
Q) Write a program to find all matches of pattern in given strings and its position? Use vector of strings?
Q) What is the difference between array an vector?
Q) What is the difference between vector, list, set and map?
Q) Why vectors are thread safe?

Q) What do you mean by " every iterator and reference after the point of resize/erase is invalidated "?
Invalidation  in vector means pointing out side of range of vector or pointing to altogether different value.
Insertion consequence in a vector:
i)All iterators and references before the point of insertion are unaffected, unless the new container size is greater than the previous capacity (in which case all iterators and references are invalidated.
ii)Erase consequences in vector: 
Every iterator and reference after the point of erase is invalidated.
iii)Resize effect in vector:
As per insertion and erase.
 example code of vector invalidation in c++ STL vector:
#include<iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
    int arr[] = { 10, 20, 30 };

    std::vector<int> vec(arr, arr + 3);
    // vector contains 1, 2, 3
        //size 3 and capasity 4

    std::vector<int>::iterator i = vec.begin();
    cout <<"*i="<< *i << endl; // prints 10
    int &ref = *i;
    cout <<"ref="<<ref << endl; // prints 10

    vec.resize(5, 100);
//vector now contains 1, 2, 3, 100, 100
//now capasity is 8 > size 5

    // WRONG! might work, crash or invalid result
    cout <<"*i=="<< *i << endl; // prints 0

    // WRONG! invalid reference
    cout <<"ref=="<<ref << endl; // prints 0

   return 0;
}

STL Map all operations example - map all algorithms

What is a map?
A map is an associative container which stores elements in key-value pair.
By default elements are stored in sorted fashion in ascending order of key. Binary search tree is internal data structure to implement maps.
How to insert in a map?
i) using 'insert" algorithm or
ii)using [key]=value style.
What is the difference between above two ways of insertion in maps?
What happens when a value is inserted in a map    ?
It depends on what algorithm has been used to insert.
i)If "insert.(pair<keyType,valuType>(key,value))" is used then value is simply gets ignored if that key already exists.
ii)If [key]=value is used then new value gets replaced if that key already exists.
iii)If at(key)=value is used then also new value is update to key.
How to delete using key?
By "find" and "erase" algorithm.
C++ MAP STL example code:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
map<int,string> m;//actually <string, int> example is more used
m.insert(pair<int,string>(1,"Ram"));
m.insert(pair<int,string>(4,"Ram"));
m.insert(pair<int,string>(8,"Ram"));
m.insert(pair<int,string>(3,"Ram"));
m.insert(pair<int,string>(5,"Ram"));
m.insert(pair<int,string>(500,"Ram"));
m.insert(pair<int,string>(50,"Ram"));
m.insert(pair<int,string>(100,"Ram"));
m[1000]="Supreme";


cout<<"map is:"<<endl;
map<int,string>::iterator itr;
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;//sorted keys

cout<<"Erase all with key 4"<<endl;
int del=m.erase(4);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"erase all less than key 8"<<endl;
m.erase(m.begin(),m.find(8));
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

//find(const g) – Returns an iterator to the element with key value ‘g’ in the map if found, else returns the iterator to end
cout<<"Finding key 100 and deleting it."<<endl;
map<int,string>::iterator itr2=m.begin();
itr2=m.find(100);
if(itr2!=m.end())
{
cout<<"100 found"<<endl;
m.erase(itr2);
//m.at(100) = "NewValue";
}
else
{
cout<<"100 not found"<<endl;
}
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Deleting key 50"<<endl;
m.erase(50);
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Inserting using at(key)"<<endl;
m.at(8) = "Raheem";
m.at(500) = "Jesus";
//m.at(100) = "God";//out of range when tries to insert at a key which does not exists
for(itr=m.begin();itr!=m.end();itr++)
cout<<itr->first<<" "<<itr->second<<endl;

cout<<"Find(key)->second display."<<endl;
cout << "8 => " << m.find(8)->second<<endl;
cout << "500 => " << m.find(500)->second<<endl;
//cout << "500 => " << m.find(100)->second<<endl;//empty

cout<<endl;
return 0;
}
Example 2:
What is the difference between two different ways of inserting into a map?
What will happen if duplicate values are inserted in a map?
i) inserting using algorthm"insert" : Does nothing. Key holds the old value.
ii) inserting using [] : update the key with new value.
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
map<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
//insert resturns false if same key is inserted again.
//Nothing happens if we insert duplicatge key.
m.insert(make_pair("Aditi",4));//Not inserted as key Aditi already exists.
m.insert(make_pair("Aditi",5));//Not inserted as key Aditi already exists.
//Different keys can have the same value as another key's value.
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

map<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Biswa 3
Manoj 1
Sony 2
*/
cout<<"Another map to show second way of inserting elements:\n";
map<string,int> m2;
m2.insert(make_pair("AAA",1));
m2.at("AAA")=300;//now value of key AAA is also gets updated
m2["BBB"]=2;//now value of key BBB is 2
m2["BBB"]=3;//now value of key BBB is 3
m2["BBB"]=4000;//now value of key BBB is 4000
map<string,int>::iterator itr2=m2.begin();
while(itr2!=m2.end())
{
cout<<itr2->first<<" "<<itr2->second<<endl;
itr2++;
}
/*
AAA300
BBB 4000
*/
return 0
 }
Multi Map example to hold duplicate keys:
#include<iostream>
using namespace std;
#include<map>
#include<algorithm>
int main()
{
cout<<""<<endl;
multimap<string,int> m;
//In map values are inserted in asending order of keys.
m.insert(pair<string,int> ("Manoj",5));
m.insert(make_pair("Sony",2));
m.insert(make_pair("Aditi",3));
m.insert(make_pair("Aditi",4));//Another Aditi with new value 4
m.insert(make_pair("Aditi",5));//Another Aditi with new value 5
m.insert(make_pair("Biswa",3));//Biswa inserted after Aditi.

multimap<string,int>::iterator itr=m.begin();
while(itr!=m.end())
{
cout<<itr->first<<" "<<itr->second<<endl;
itr++;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
*/
cout<<"---map example to find a key"<<endl;
cout<<"---find returns iterator to the found keys"<<endl;
cout<<"---find returns false so garbage value"<<endl;
itr=m.begin();
cout<<"m.find(Aditi)="<<m.find("Aditi")->second<<endl;//3//first match only.
cout<<"m.find(Manoj)="<<m.find("Manoj")->second<<endl;//5
cout<<"m.find(Sahu)="<<m.find("Sahu")->second<<endl;//garbage

itr=m.begin();
if(m.find("Aditiii")!=m.end())
cout<<itr->first<<" found and value is "<<itr->second<<endl;
else
cout<<"Not found"<<endl;

return 0;
}
/*
Aditi 3
Aditi 4
Aditi 5
Biswa 3
Manoj 5
Sony 2
---map example to find a key
---find returns iterator to the found keys
---find returns false so garbage value
m.find(Aditi)=3
m.find(Manoj)=5
m.find(Sahu)=223444160
Not found
*/ 
In multi map "find" return the value of first key only.
How to find all the values associated with duplicate key?
Using the algorithm equal_range("key").
Count can be taken by algorithm "distance" 

STL Vector example in C++ in Linux all operations

//Vector is a STL container. Vector is template type container, which can store any type of element by providing type in template arguments. Vector size expanded to double or shrinks dynamically at run time. Just like array memory is allocated contagiously but unlike array it is stored in heap. 
//vector is should be preferred as compared to dynamic array because
//1.memory is automatically freed in case of vector on destruction
//2.vector is implemented internally as dynamic array in heap which
//shrinks and grows automatically so no wastage of memory
//3. It is fast as elements can be accessed randomly by index just like arrays.
For understanding:
No of elt  size  capasity
0              0       0
1              1       1 
2              2       2
3              3       4
4              4       4
5              5       8
6              6       8
7              7       8
8              8       8 
9              9       16
10           10      16
17            17     32 
Example:       
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
int main()
{
vector<string> myvector;
cout<<"-----"<<"Inserting at end using pushback is efficient in vector as no shift:"<<endl;
myvector.push_back("cccc");
myvector.push_back("bbbb");
myvector.push_back("eeee");
myvector.push_back("aaaa");
myvector.push_back("dddd");
cout<<"-----"<<"Size of the vector is:"<<myvector.size()<<endl;

cout<<"-----"<<"Traversing vector with iterator:"<<endl;
vector<string>::iterator it;
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n----"<<"Traversing vector with index subscripts:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//mind the syntax to display//cccc bbbb eeee aaaa dddd

cout<<"\n-------"<<"Sorting vector elements in ascending order:"<<endl;
sort(myvector.begin(),myvector.end());
for(it=myvector.begin();it!=myvector.end();it++)
cout<<*it<<" ";//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Finding a string in a vector of strings:"<<endl;
int pos;string elt="bbbb";
pos=find(myvector.begin(),myvector.end(),elt)-myvector.begin();
if(pos<myvector.size())//
cout<<"bbbb found at index:"<<pos<<endl;//bbbb at 1st index
else
cout<<"Not found"<<endl;

cout<<"------------"<<"Vector before erasing is:"<<endl;
for(int i=0;i<myvector.size();i++)
cout<<myvector.at(i);//aaaa bbbb cccc dddd eeee

cout<<"\n------------"<<"Erasing 1st index element ie bbbb of vector"<<endl;
myvector.erase(myvector.begin()+1);//deleting 1st index leaving 0th index elt
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//aaaa cccc dddd eeee

cout<<"\n------------"<<"Erasing first 2 elements:"<<endl;
myvector.erase(myvector.begin(), myvector.begin()+2);//2 elements and not 2 index
cout<<"Now vector is:";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//dddd eeee

cout<<"\n------------"<<"clear deletes all the elts of a vector"<<endl;
//Removes all elements from the vector (which are destroyed), leaving the container with a size of 0.
myvector.clear();
for(int i=0;i<myvector.size();i++)
cout<<myvector[i];//empty

cout<<"------------"<<"Inserting method 2 in vector"<<endl;
myvector.push_back("ffff");
myvector.push_back("gggg");

cout<<"------------"<<"pop_back in vector to delete from last"<<endl;
while(!myvector.empty())
{
cout<<myvector.back();//gggg ffff
myvector.pop_back();
}//vector is empty now
cout<<"\nInserting after 0th elt";
vector<string>::iterator itr2=myvector.begin();
myvector.insert(itr2,"bbbb");
myvector.insert(itr2,"pppp");
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp bbbb

cout<<"\nInserting after nth elt";
vector<string>::iterator itr22=myvector.begin();
myvector.insert(itr22+1,"hhhh");//insert hhhh after pppp
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];//pppp hhhh bbbb

cout<<"\n------------"<<"Finding other way:"<<endl;
vector<string>::iterator itr;
itr=find(myvector.begin(),myvector.end(),"pppp");
if(itr!=myvector.end())
{
cout<<"pppp found at position:"<<itr-myvector.begin()<<endl;//1
//deleting found element as
myvector.erase(itr);
}
else
{
cout<<"Not found"<<endl;
}
cout<<"After deleting pppp vector becomes:::\n";
for(int i=0;i<myvector.size();i++)
cout<<" "<<myvector[i];// hhhh bbbb

cout<<"\n------------"<<"Reverse a vecotr:"<<endl;
reverse(myvector.begin(),myvector.end());
for(int i=0;i<myvector.size();i++)
cout<<myvector[i]<<" ";//bbbb hhhh pppp

cout<<"\n------------"<<"insert repeated values"<<endl;
//exchanges elements of vectors even difference in sizes
vector<int> vec1 (3,100);   // three ints with a value of 100
vector<int> vec2 (5,200);   // five ints with a value of 200
vec1.swap(vec2);
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n------------"<<"Delete all occurence of an element from vector"<<endl;
vec1.erase(remove(vec1.begin(), vec1.end(), 200), vec1.end());
for(int i=0;i<vec1.size();i++)
cout<<vec1[i]<<" ";//becomes 200 200 200 200 200

cout<<"\n-------------"<<"Finding and deleting a particular element in a vector."<<endl;
//vector<int> vect3{20,30,40,111,111,11,60};//need to compile with -std=c++11
vector<int> vect3;
vect3.push_back(20);
vect3.push_back(30);
vect3.push_back(40);
vect3.push_back(111);
vect3.push_back(111);
vect3.push_back(11);
vect3.push_back(60);
int count=0;
for( vector<int>::iterator iter = vect3.begin(); iter != vect3.end(); ++iter )
{
count++;
    if( *iter == 111 )
    {
cout<<"111 found at: "<<count<<" and "<<vect3.at(count);
        vect3.erase( iter );
        break;
    }
}
cout<<"\nNow vector is:"<<endl;
for(int i=0;i<vect3.size();i++)
cout<<vect3[i]<<" ";//becomes 20 30 40 111 11 60

cout<<"\n----Find and replace in a vector of integers"<<endl;
int myints[] = { 11, 22, 33, 33, 11, 11, 22, 44,55,66 };
vector<int> myvector2 (myints, myints+10);            // 11 22 33 33 11 11 22 44 55 66
replace (myvector2.begin(), myvector2.end(), 22, 222); // 11 222 33 33 11 11 222 44 55 66

cout << "myvector2 contains:";
for (vector<int>::iterator it=myvector2.begin(); it!=myvector2.end(); ++it)
cout <<" "<< *it;//10 99 30 30 99 10 10 99

cout<<endl;
return 0;
}
/*
OUTPUT:
------------Inserting at end using pushback is efficient in vector as no shift:
------------Size of the vector is:5
------------Traversing vector with iterator:
cccc bbbb eeee aaaa dddd
------------Traversing vector with index subscripts:
ccccbbbbeeeeaaaadddd
------------Sorting vector elements in ascending order:
aaaa bbbb cccc dddd eeee
------------Finding a string in a vector of strings:
bbbb found at index:1
------------Vector before erasing is:
aaaabbbbccccddddeeee
------------Erasing 1st index element ie bbbb of vector
Now vector is: aaaa cccc dddd eeee
------------Erasing first 2 elements:
Now vector is: dddd eeee
------------clear deletes all the elts of a vector
------------Inserting method 2 in vector
------------pop_back in vector to delete from last
ggggffff
Inserting after 0th elt pppp bbbb
Inserting after nth elt pppp hhhh bbbb
------------Finding other way:
pppp found at position:0
After deleting pppp vector becomes:::
 hhhh bbbb
------------Reverse a vecotr:
bbbb hhhh
------------insert repeated values
200 200 200 200 200
------------Delete all occurence of an element from vector

-------------Finding and deleting a particular element in a vector.
111 found at: 4 and 111
Now vector is:
20 30 40 111 11 60

*/
/*Vector is internally implemented as dynamically allocated array.eg. if size is not know then int *p = new in[size].http://www.cplusplus.com/doc/tutorial/dynamic/ Non dynamic array example is int array[SIZE];wastage of unused memory. In dynamic array only pointer to array is static. So vector is used for efficient memory allocation when insert is at last scenarios.
As the vectors use an array as their underlying storage, inserting elements in positions other than the vector end causes the container to relocate all the elements that were after position to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).*/