Decimal to Binary
//C program to convert decimal to binary
#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a decimal number:";//13
cin>>num;
int n,r,i=1;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%2;//13%2=1 //6%2=0 //3%2=1 //1%2=1//
n=n/2;//13/2=6 //6/2=3 //3/2=1 //1/2=0
s=s+r*i;//0+1*1=1 //1+0*10=1 //1+1*100=101 //101+1*1000=1101
i=i*10;//1*10=10//10*10=100 //100*10=1000 //10000
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"Decimal number "<<num<<" in binary is: "<<s<<endl;//1101
return 0;
}
/*
Enter a decimal number:13
r=1 n=6 s=1 i=10
r=0 n=3 s=1 i=100
r=1 n=1 s=101 i=1000
r=1 n=0 s=1101 i=10000
Decimal number 13in binary is: 1101
*/
//Binary to Decimal
#include<iostream>
using namespace std;
#include<math.h>
int main()
{
cout<<"manin()\n";
int num;
cout<<"Enter a binary number:";//1101=13
cin>>num;
int n,r,i=0;
unsigned long s=0;
n=num;
while(n>0)
{
r=n%10;//
n=n/10;//
s=s+r*pow(2,i);//
++i;
cout<<"r="<<r<<" n="<<n<<" s="<<s<<" i="<<i<<endl;
}
cout<<"binary number "<<num<<" in Decimal is: "<<s<<endl;//1101
return 0;
}
/*
manin()
Enter a binary number:1101
r=1 n=110 s=1 i=1
r=0 n=11 s=1 i=2
r=1 n=1 s=5 i=3
r=1 n=0 s=13 i=4
binary number 1101 in Decimal is: 13
*/
//Sum of digits of a numbers
#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1//1/10=0
sum=sum+r;//4//4+3//4+3+2//4+3+2+1=10
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//10
return 0;
}
//Reverse Number
#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
cout<<"sum of "<<num<<" is "<<sum<<endl;//4321
return 0;
}
//Pallindrom number
#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int num,n,r,sum=0;
cout<<"Enter a number:";
cin>>num;//1234
n=num;
while(n>0)
{
r=n%10;//4//3//2//1%10=1
n=n/10;//123//12//1// 1/10=0
sum=sum*10+r;//0*10+4=4//4*10+3=40+3=43//43*10+2=430+2=432//432*10+1=4320+1=4321
}
if(num==sum)
{
cout<<"Its a pallindrom "<<num<<" is equal to "<<sum<<endl;//4321
}
else
{
cout<<"Not a pallindrom.\n";
}
return 0;
}
//Reversing String
#include<iostream>
using namespace std;
#include<string.h>
void strRev(char *arr);
int main()
{
cout<<"manin()\n";
char arr[]="Hello";
///*
int result;
char *end;
char *start;
end=arr;
start=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<=l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
//*/
cout<<"reversed string is:"<<arr<<endl;
cout<<"\nAgain reversing using function:\n";
strRev(arr);
cout<<"arr is now again: "<<arr<<endl;
//cout<<"Reverse string is: "<<strRev(arr)<<endl;
return 0;
}
void strRev(char *arr)
{
char *start=arr;
char *end=arr;
int l,i;
char t;
l=strlen(arr);
for(i=0;i<l-1;i++)
end++;
for(i=0;i<l/2;i++)
{
t=*start;
*start=*end;
*end=t;
start++;
end--;
}
}
/*
manin()
reversed string is:olleH
Again reversing using function:
arr is now again: Hello
*/
C program to merge two sorted arrays. Array Union
//C/C++/C Plus Plus program to merge two sorted arrays
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>
int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);
cout<<endl;
}
//output
//12345789
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>
int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);
cout<<endl;
}
//output
//12345789
C program to find common numbers in two sorted arrays. Array intersection
//C/C++/C Plus Plus program to find common numbers in two sorted arrays
//C/C++/C Plus Plus program to find intersection of two sorted arrays
//C/C++/C Plus Plus program to find common elements of two sorted arrays
#include<iostream>
using namespace std;
int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr1[i])
j++;
else //arr[i]==arr[j]
{
cout<<"common elements are:"<<arr2[j]<<endl;
i++;
j++;
}
}
}
//C/C++/C Plus Plus program to find intersection of two sorted arrays
//C/C++/C Plus Plus program to find common elements of two sorted arrays
#include<iostream>
using namespace std;
int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
i++;
else if(arr2[j]<arr1[i])
j++;
else //arr[i]==arr[j]
{
cout<<"common elements are:"<<arr2[j]<<endl;
i++;
j++;
}
}
}
C Program for sorting an array using Bubble Sort and Insertion Sort
#include<iostream>
using namespace std;
int main()
{
cout<<"manin()\n";
int arr[20],n,i,j,t;
cout<<"Enter the number of elements in array:"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
cin>>arr[i];
cout<<"Entered the elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
/*
cout<<"Bubble sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
cout<<n-i-1<<" "<<j<<" "<<j+1<<" "<<endl;
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
*/
//OR
/*
Selection sort: By first scanning the entire list before locating the exact pair of numbers to swap, only two writes to memory are performed by Selection Sort for each O(n) scan,whereas
Bubble Sort does writes on each and every comparison. So, Bubble Sort does O(n^2) writes. while selection sort does O(n) writes to mwmory.
*/
cout<<"\nSelection sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)//mind n-1
{
for(j=i+1;j<n;j++) //mind n
{
if(arr[i]>arr[j])
{
cout<<n<<" "<<i<<" "<<j<<" "<<endl;
t=arr[j];
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
cout<<"Sorted array elements are:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
/*
//Selection Sort:
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
4 1 2
4 2 3
4 3 4
4 4 5
3 2 3
3 3 4
3 4 5
2 3 4
2 4 5
1 4 5
Sorted array elements are:
1 2 3 4 5
//Bubble sort
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
5 0 1
5 0 2
5 0 3
5 0 4
5 1 2
5 1 3
5 1 4
5 2 3
5 2 4
5 3 4
Sorted array elements are:
1 2 3 4 5
*/
/*
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.
Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better
For both insertion and bubble sort worst case is O(n^2)
*/
using namespace std;
int main()
{
cout<<"manin()\n";
int arr[20],n,i,j,t;
cout<<"Enter the number of elements in array:"<<endl;
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
cin>>arr[i];
cout<<"Entered the elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
/*
cout<<"Bubble sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
cout<<n-i-1<<" "<<j<<" "<<j+1<<" "<<endl;
t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
*/
//OR
/*
Selection sort: By first scanning the entire list before locating the exact pair of numbers to swap, only two writes to memory are performed by Selection Sort for each O(n) scan,whereas
Bubble Sort does writes on each and every comparison. So, Bubble Sort does O(n^2) writes. while selection sort does O(n) writes to mwmory.
*/
cout<<"\nSelection sort to arrange in ascending order:"<<endl;
for(i=0;i<n-1;i++)//mind n-1
{
for(j=i+1;j<n;j++) //mind n
{
if(arr[i]>arr[j])
{
cout<<n<<" "<<i<<" "<<j<<" "<<endl;
t=arr[j];
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
cout<<"Sorted array elements are:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
/*
//Selection Sort:
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
4 1 2
4 2 3
4 3 4
4 4 5
3 2 3
3 3 4
3 4 5
2 3 4
2 4 5
1 4 5
Sorted array elements are:
1 2 3 4 5
//Bubble sort
manin()
Enter the number of elements in array:
5
Enter the elements:5
4
3
2
1
Entered the elements:
5 4 3 2 1
Selection sort to arrange in ascending order:
5 0 1
5 0 2
5 0 3
5 0 4
5 1 2
5 1 3
5 1 4
5 2 3
5 2 4
5 3 4
Sorted array elements are:
1 2 3 4 5
*/
/*
In Bubble sort , at every iteration you find a largest number and push it to bottom (Bubble out larger number)
In Insertion sort you have two regions one sorted and another unsorted.
At Every Iteration you pick up an element from unsorted region and insert at proper location in Sorted region.
Insertion Sort and Bubble sort both have Worst Case O(N^2).
But if the array is mostly sorted Insertion Sort will perform better
For both insertion and bubble sort worst case is O(n^2)
*/
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;
}
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"
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"
What are QML FAQ in interviews?
Q) What is Qml ?
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
Q) How to call c++ call from QML?
QML call C + + methods with the Qt meta-object system. Like below:
onClicked: parent.color = parent.randomColor ()
Q) What are Four ways of integreting C++ with Qml?
Subclassing QQuickItem: QQuickItem allows you to write your own visual and non-visual QML items using C++.
Registering C++ types with QML: C++ classes can be registered with the QML type system, allowing them to be instantiated as QML types.
Registering Context Properties: QObjects can be registered with the QML context, allowing their properties to be directly accessed.
Accessing QML objects through the QML object tree: All QML objects reside in a tree hierarchy and can be accessed via the root of the tree.
http://www.ics.com/blog/multilayered-architecture-qt-quick
Q) How to call a C++ function from a qml?
Through setcontext property.
Note
Loading a main.qml with a simple Item as the root type through the QmlApplicationEngine will not show anything on your display, as it requires a window to manage a surface for rendering. The engine is capable of loading qml code which does not contain any user interface (e.g plain objects). Because of this it does not create a window for you by default.
The qmlscene or the new qml runtime will internally first check if the main qml file contains a window as a root item and if not create one for you and set the root item as a child to the newly created window.
Q)What is Q_INVOKABLE?
Add callable methods using Q_INVOKABLE or Qt slots, and connect to Qt signals with an onSignal syntax
Q)How to call a QML function from c++?
QML functions can be called from C++ and vice-versa.
All QML functions are exposed to the meta-object system and can be called usingQMetaObject::invokeMethod(). Here is a C++ application that uses this to call a QML function:
// MyItem.qml
import QtQuick 1.0
Item {
function myQmlFunction(msg) {
console.log("Got message:", msg)
return "some return value"
}
}
// main.cpp
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();
QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));
qDebug() << "QML function returned:" << returnedValue.toString();
delete object;
Q)How to call a C++ function from QML ?
A C++ function can be called from a qml using set contextpropery in c++.
http://doc.qt.io/qt-4.8/qtbinding.html
All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal.
The signal is sent to QML, and the slot is invoked from QML.
There are different ways to send signals from C++ to QML and back. In this article, we show how to do this by embedding a C++ class directly into QML. This has the advantage that no Qt::connect connections need to be set-up manually.
In our example, we have a Receiver class that is implemented in C++.
This class defines a signal sendToQml and a slot receiveFromQml.
Both have an integer parameter.
The signal is sent to QML, and the slot is invoked from QML.
Example:
//signal_slot.pro
TEMPLATE = app
QT += qml quick
#export QT_SELECT=5
SOURCES += main.cpp \
receiver.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
HEADERS += \
receiver.h
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "receiver.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Receiver receiver;
QQmlContext* ctx = engine.rootContext();
ctx->setContextProperty("receiver", &receiver);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
receiver.sendToQml(43);
//QDeclarativeView view;
//view.rootContext()->setContextProperty("_EBSCModel",m_EBSCDtcDataModel);
//sourcePath = "qrc:///DTC/qml/ITSDTC.qml";
//view.setSource(QUrl(sourcePath));
return app.exec();
}
//receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class Receiver : public QObject
{
Q_OBJECT
public:
explicit Receiver(QObject *parent = 0);
signals:
void sendToQml(int count);
public slots:
void receiveFromQml(int count);
};
#endif // RECEIVER_H
//receiver.cpp
#include "receiver.h"
#include <QDebug>
Receiver::Receiver(QObject *parent) :
QObject(parent)
{
}
void Receiver::receiveFromQml(int count) {
qDebug() << "Received in C++ from QML:" << count;
}
//main.qml
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
id: test
visible: true
width: 200
height: 50
Connections {
target: receiver
onSendToQml: {
console.log("Received in QML from C++: " + count)
}
}
MouseArea {
anchors.fill: parent
onClicked: {
receiver.receiveFromQml(42);
}
}
Text {
text: qsTr("Press me to send a signal to C++")
anchors.centerIn: parent
}
}
QML is the name of the language (just like C++, which is another language...)
QML stands for Qt Meta Language or Qt Modelling Language is a user interface markup language.
Q) How to call c++ call from QML?
QML call C + + methods with the Qt meta-object system. Like below:
onClicked: parent.color = parent.randomColor ()
Q) What are Four ways of integreting C++ with Qml?
Subclassing QQuickItem: QQuickItem allows you to write your own visual and non-visual QML items using C++.
Registering C++ types with QML: C++ classes can be registered with the QML type system, allowing them to be instantiated as QML types.
Registering Context Properties: QObjects can be registered with the QML context, allowing their properties to be directly accessed.
Accessing QML objects through the QML object tree: All QML objects reside in a tree hierarchy and can be accessed via the root of the tree.
http://www.ics.com/blog/multilayered-architecture-qt-quick
Q) How to call a C++ function from a qml?
Through setcontext property.
Note
Loading a main.qml with a simple Item as the root type through the QmlApplicationEngine will not show anything on your display, as it requires a window to manage a surface for rendering. The engine is capable of loading qml code which does not contain any user interface (e.g plain objects). Because of this it does not create a window for you by default.
The qmlscene or the new qml runtime will internally first check if the main qml file contains a window as a root item and if not create one for you and set the root item as a child to the newly created window.
Q)What is Q_INVOKABLE?
Add callable methods using Q_INVOKABLE or Qt slots, and connect to Qt signals with an onSignal syntax
Q)How to call a QML function from c++?
QML functions can be called from C++ and vice-versa.
All QML functions are exposed to the meta-object system and can be called usingQMetaObject::invokeMethod(). Here is a C++ application that uses this to call a QML function:
// MyItem.qml
import QtQuick 1.0
Item {
function myQmlFunction(msg) {
console.log("Got message:", msg)
return "some return value"
}
}
// main.cpp
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();
QVariant returnedValue;
QVariant msg = "Hello from C++";
QMetaObject::invokeMethod(object, "myQmlFunction",
Q_RETURN_ARG(QVariant, returnedValue),
Q_ARG(QVariant, msg));
qDebug() << "QML function returned:" << returnedValue.toString();
delete object;
Q)How to call a C++ function from QML ?
A C++ function can be called from a qml using set contextpropery in c++.
http://doc.qt.io/qt-4.8/qtbinding.html
All QML signals are automatically available to C++, and can be connected to using QObject::connect() like any ordinary Qt C++ signal.
The signal is sent to QML, and the slot is invoked from QML.
There are different ways to send signals from C++ to QML and back. In this article, we show how to do this by embedding a C++ class directly into QML. This has the advantage that no Qt::connect connections need to be set-up manually.
In our example, we have a Receiver class that is implemented in C++.
This class defines a signal sendToQml and a slot receiveFromQml.
Both have an integer parameter.
The signal is sent to QML, and the slot is invoked from QML.
Example:
//signal_slot.pro
TEMPLATE = app
QT += qml quick
#export QT_SELECT=5
SOURCES += main.cpp \
receiver.cpp
RESOURCES += qml.qrc
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Default rules for deployment.
include(deployment.pri)
HEADERS += \
receiver.h
//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "receiver.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
Receiver receiver;
QQmlContext* ctx = engine.rootContext();
ctx->setContextProperty("receiver", &receiver);
engine.load(QUrl(QStringLiteral("qrc:///main.qml")));
receiver.sendToQml(43);
//QDeclarativeView view;
//view.rootContext()->setContextProperty("_EBSCModel",m_EBSCDtcDataModel);
//sourcePath = "qrc:///DTC/qml/ITSDTC.qml";
//view.setSource(QUrl(sourcePath));
return app.exec();
}
//receiver.h
#ifndef RECEIVER_H
#define RECEIVER_H
#include <QObject>
class Receiver : public QObject
{
Q_OBJECT
public:
explicit Receiver(QObject *parent = 0);
signals:
void sendToQml(int count);
public slots:
void receiveFromQml(int count);
};
#endif // RECEIVER_H
//receiver.cpp
#include "receiver.h"
#include <QDebug>
Receiver::Receiver(QObject *parent) :
QObject(parent)
{
}
void Receiver::receiveFromQml(int count) {
qDebug() << "Received in C++ from QML:" << count;
}
//main.qml
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
id: test
visible: true
width: 200
height: 50
Connections {
target: receiver
onSendToQml: {
console.log("Received in QML from C++: " + count)
}
}
MouseArea {
anchors.fill: parent
onClicked: {
receiver.receiveFromQml(42);
}
}
Text {
text: qsTr("Press me to send a signal to C++")
anchors.centerIn: parent
}
}
Subscribe to:
Posts (Atom)