শনিবার, ২৬ সেপ্টেম্বর, ২০১৫

STL C++ List

STL list intro :



 //STL Container list  
 #include <bits/stdc++.h>  
 #define p_l_i(l) for(list<int>::iterator it = l.begin();it!=l.end();it++)cout<<*it<<" ";cout<<endl;  
 using namespace std;  
 int main()  
 {  
   list<int>l1;  
   list<int>l2(9);  
   list<int>l3(7,45);  
   list<int>l4(l3.begin(),l3.end()); //Can't do list<int>l4(l3.begin() + 2 ,l3.end() - 1);  
   list<int>l5(l3);  
   if(l1.empty())  
     cout<<"l1 is empty!\n";  
   p_l_i(l2);  
   p_l_i(l3);  
   p_l_i(l4);  
   p_l_i(l5);  
   //FOR ALL SEQUENCE CONTAINERS v1=v2;d1=d2;l1=l2 is valid where v1 takes all values of v2 or v1 is transformed into v2  
   l2.push_back(3);  
   l2.push_front(6);  
   p_l_i(l2);  
   l3.pop_back();  
   l3.pop_front();  
   p_l_i(l3);  
 //Inserting just 1 element  
 //First construct the proper iterator  
 list<int>::iterator lit = l2.begin();         //l2 : 6 0 0 0 0 0 0 0 0 0 3  
 lit++; //after this instruction lit will point to 2nd position ^  
 l2.insert(lit,99); //l2 : 6 99 0 0 0 0 0 0 0 0 0 3  
 p_l_i(l2); //lit points to   ^  
 //So,if I insert 3 at lit it'll be inserted at position 3 (not 2)  
 l2.insert(lit,3); //l2 : 6 99 3 0 0 0 0 0 0 0 0 0 3  
 p_l_i(l2); //lit points to   ^  
 l2.push_back(23);  
 l2.push_back(45);  
 l2.push_back(77); //l2 : 6 99 3 0 0 0 0 0 0 0 0 0 3 23 45 77  
 //Lets insert 65 at the third position from last (where is 23?)  
 lit = l2.end(); //It points to next slot to the last position  
 lit--; //It 'll now point to the last position (where is 77?)  
 for(int a=0;a<2;a++) //how many steps does it take to move from 77 to 23 .Yeah,it's 2 !  
 lit--; //equivalent to lit-=3 But can't do that  
 l2.insert(lit,65); ////l2 : 6 99 3 0 0 0 0 0 0 0 0 0 3 65 23 45 77  
 p_l_i(l2); //lit now points to              ^  
 //Inserting more than 1 element  
 l2.insert(lit,4,8); //Inserting 4 8s in the position of 23  
 p_l_i(l2); //l2 : 6 99 3 0 0 0 0 0 0 0 0 0 3 65 8 8 8 8 23 45 77  
                           // ^  
 vector<int>vi;  
 vi.push_back(12);  
 vi.push_back(13);  
 vi.push_back(14);  
 vi.push_back(15);  
 vi.push_back(16);  
 vi.push_back(17);  
 //Inserting a total vector or part of it  
 l2.insert(--lit,vi.begin()+2,vi.end());//inserting 14 15 16 17 where the last 8 is (pre-incremented)  
 //l2 : 6 99 3 0 0 0 0 0 0 0 0 0 3 65 8 8 8 14 15 16 17 8 23 45 77  
                          //  ^  
 p_l_i(l2);  
 return 0;  
 }  

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন