Wednesday, 11 May 2011

Example of set_union and set_intersection

Program as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>

using namespace
std;

int
main()
{

int
setOne[] = {5, 10, 15, 20, 25};
int
setTwo[] = {50, 40, 30, 20, 10, 11, 21, 31, 41, 51};

int
setOneSize = sizeof(setOne) / sizeof(int);
int
setTwoSize = sizeof(setTwo) / sizeof(int);

//Its necessary to sort if not already sorted
sort(setTwo, setTwo + setTwoSize);

vector<int> unionSetVector(setOneSize + setTwoSize);
set_union(setOne, setOne + setOneSize, setTwo, setTwo + setTwoSize, unionSetVector.begin());

cout<<"\n1. unionSetVector : ";
copy(unionSetVector.begin(), unionSetVector.end(), ostream_iterator<int>(cout, " "));
cout<<endl;

vector<int> intersectionSetVector(min(setOneSize, setTwoSize));
set_intersection(setOne, setOne + setOneSize, setTwo, setTwo + setTwoSize, intersectionSetVector.begin());

cout<<"\n1. intersectionSetVector : ";
copy(intersectionSetVector.begin(), intersectionSetVector.end(), ostream_iterator<int>(cout, " "));
cout<<endl;

cout<<endl;
return
0;
}


The output is as follows:

Tuesday, 3 May 2011

Example of 'Set' and operations

Example of Set and operations as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include <set>

using namespace
std;

int
main()
{

int
someInts[] = {3, 6, 9, 12, 15, 18};
int
someIntsSize = sizeof(someInts) / sizeof(int);

set<int> someSet (someInts, someInts + someIntsSize);

cout<<"\n1. someSet : ";
copy(someSet.begin(), someSet.end(), ostream_iterator<int>(cout, " "));
cout<<endl;

//Insert some more elements
someSet.insert(0);
someSet.insert(10);
someSet.insert(20);

cout<<"\n2. someSet : ";
copy(someSet.begin(), someSet.end(), ostream_iterator<int>(cout, " "));
cout<<endl;

//Upper Bound means the next greater number
set<int>::iterator it = someSet.upper_bound(5);
cout << "\nupper_bound(5) = " << *it << endl;

it = someSet.upper_bound(10);
cout << "\nupper_bound(10) = " << *it << endl;

//Lower bound means either equal or greater number
it = someSet.lower_bound(5);
cout << "\nlower_bound(5) = " << *it << endl;

it = someSet.lower_bound(10);
cout << "\nlower_bound(10) = " << *it << endl;

//Equal Range returns a pair
pair<set<int>::iterator,set<int>::iterator> retIt;
retIt = someSet.equal_range(5);
cout<<"\nequal_range(5) - lower bound = " << *retIt.first <<
" upper bound = "
<< *retIt.second << endl;

retIt = someSet.equal_range(10);
cout<<"\nequal_range(10) - lower bound = " << *retIt.first <<
" upper bound = "
<< *retIt.second << endl;

cout<<endl;
return
0;
}


The output is as follows:

Wednesday, 27 April 2011

Example of Algorithm Copy

Sometimes its useful to know the 'copy' method in algorithm class. The following is an example:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

//OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result );

#include<iostream>
#include <algorithm>
#include <vector>

using namespace
std;

int
main()
{

int
someInts[] = {10, 20, 20, 40, 50};
int
someMoreInts[] = {100, 200, 300, 400, 500, 600, 700};

vector<int> someVector;
vector<int>::iterator someIterator;

//Get the total size of all elements
int totalSize = (sizeof(someInts) + sizeof(someMoreInts)) / sizeof(int);

//Resize someVector to right size
someVector.resize(someVector.size() + totalSize);

//Get the number of elements of someInts
int tempSize = sizeof(someInts) / sizeof(int);

vector<int>::iterator finalElementIt = copy(someInts, someInts + tempSize, someVector.begin());

cout<<"\n1. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

//Get size of someMoreInts
tempSize = sizeof(someMoreInts) / sizeof(int);

copy(someMoreInts, someMoreInts + tempSize, finalElementIt);

cout<<"\n2. someVector contains :";
for
(someIterator = someVector.begin(); someIterator != someVector.end(); ++someIterator)
cout<<" "<<*someIterator;
cout<<endl;

return
0;
}


The output is as follows:

Wednesday, 20 April 2011

An Challenging Interview question with a difference

The following program is provided:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int i) {}
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}


As already mentioned above, the expected output of 161700 is provided. The class 'SR' could be written as one wishes. How to do write the class 'SR' to get the desired output?
.
.
.
.
Give it a try before looking at the solution.
.
.
.
.
.
The modified program with the correct 'SR' class as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

using namespace
std;

//This class can be designed as you wish
class SR
{

public
:
SR(int& i):ref(i)
{

var = i;
}
~
SR()
{

ref = var;
}

private
:
int
var;
int
&ref;
};


int
main()
{

int
sum = 0;
for
(int i = 1; i < 100; i++)
{

SR ii(i);
while
(i--)
sum += i;
}

cout<<"Expected value of sum = 161700" << endl;
cout<<"Returned value of sum = " << sum << endl;

return
0;
}



Source: Modified from here. Another similar question is available here.

Tuesday, 12 April 2011

isNumeric()

For some reason many C++ programmers believe there is an isNumeric() function available as part of the language. In fact I was searching for the header file to include to get a piece of code to work.

Its not difficult to create a function that will be able to check if the string is numeric or not. Here is the code.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <string>
#include <sstream>

using namespace
std;

bool
isNumeric1(string stringToCheck)
{

bool
numeric = false;

if
(stringToCheck.find_first_not_of("0123456789.") == string::npos)
numeric = true;

return
numeric;
}


bool
isNumeric2(string stringToCheck)
{

bool
numeric = true;
unsigned
i = 0;

while
(numeric && i < stringToCheck.length())
{

switch
(stringToCheck[i])
{

case
'0': case '1': case '2': case '3': case '4': case '5':
case
'6': case '7': case '8': case '9': case '.':
//do nothing
break;
default
:
numeric = false;
}

i++;
}


return
numeric;
}


bool
isNumeric3(string stringToCheck)
{

stringstream streamVal(stringToCheck);
double
tempVal;

streamVal >> tempVal; //If numeric then everything transferred to tempVal

if
(streamVal.get() != EOF)
return
false;
else
return
true;
}


int
main()
{

string str1("123"), str2("134.567"), str3("12AB");
cout << "Approach 1" << endl;
cout << str1 << (isNumeric1(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric1(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric1(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 2" << endl;
cout << str1 << (isNumeric2(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric2(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric2(str3) ? " is Numeric" : " is Not Numeric") << endl;

cout << "\nApproach 3" << endl;
cout << str1 << (isNumeric3(str1) ? " is Numeric" : " is Not Numeric") << endl;
cout << str2 << (isNumeric3(str2) ? " is Numeric" : " is Not Numeric") << endl;
cout << str3 << (isNumeric3(str3) ? " is Numeric" : " is Not Numeric") << endl;

return
0;
}




Output is as follows:


There are few problems in the program above:

1. It does not cater for negative numbers
2. It will return wrong result when you have incorrect string like 12.34.56.78

I have intentionally left it as an exercise.

Other approaches are possible as well. Why not try and think of an approach yourself.

Tuesday, 5 April 2011

string::find_next()

I met this new starter who has come from Java background. He was upset because he couldn't find string::find_next() as C++ function. He said Java is much more flexible this way. In reality, its not that bad if you look at the definition of find carefully.

size_t find ( const string& str, size_t pos = 0 ) const;
size_t find ( const char* s, size_t pos, size_t n ) const;
size_t find ( const char* s, size_t pos = 0 ) const;
size_t find ( char c, size_t pos = 0 ) const;

The first one works as find_next as I show in the example below:

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy

#include <iostream>
#include <string>

using namespace
std;

int
main()
{

string someString("Tom is not in. Infact Tom is not going to be in Tomorrow or day after Tomorrow");
string findTheString("Tom");

unsigned
position = 0;

position = someString.find(findTheString);
cout<<"First position of " << findTheString << " is " << position << endl;

//We want to find all the next positions which is after position + findTheString.length()
while(position != string::npos)
{

position = someString.find(findTheString, (position + findTheString.length()));
cout<<"Next position of " << findTheString << " is " << position << endl;
}


return
0;
}



The output is as follows:

Exercise for new programmers:
  1. The last two Tom's are part of 'Tomorrow', how can you make sure they are not printed
  2. The last Tom which is 4294... is equal to -1 or string::npos. How can you stop that being printed without making another check for string::npos
Please dont post answers as they should be trivial exercise and you should be able to figure out without much problems.

Tuesday, 29 March 2011

Reading file names from directory

The other day I had to read all the file names from a directory and I found it really difficult to write a simple program to do that. While searching I ended up at Stack Overflow and the following example is taken from here.

Note that the 'dirent.h' is not available as standard windows file and the best option is to download it from here and add it in your include directory of the project.

The program as follows:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>

#pragma warning( disable : 4996 )
#include "dirent.h"
#pragma warning( default : 4996 )

using namespace
std;

int
main(int argc, char *argv[])
{

if
(argc != 2)
{

cout<<"Usage: "<<argv[0]<<" <Directory name>"<<endl;
return
-1;
}


DIR *dir;
dir = opendir (argv[1]);
if
(dir != NULL)
{

cout<<"Directory Listing for "<<argv[1]<<" : "<<endl;
struct
dirent *ent;
while
((ent = readdir (dir)) != NULL)
{

cout<<ent->d_name<<endl;
}
}

else

{

cout<<"Invalid Directory name"<<endl;
return
-1;
}


return
0;
}

Note that in this program we put Command-line arguments argc and argv. What this means is that the final .exe is run using command prompt and the first parameter will be exe file name and the second parameter will be the directory path or you can add the directory path in Debugging->Command arguments of the properties

You may also encounter the following warning

warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

to get rid of it, I have used the #Pragma supressor.

You may also get the following error:

error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'char *' to 'LPCWSTR'
to get rid of it, go to properties->general->Character set - default is 'Use Unicode Charachter set', change it to 'Use Multi-Byte Character Set'

The output is as follows:

Tuesday, 22 March 2011

Reading Files into Vector

Thought of this while trying to create a parser. The intention is to read a complete text file into a vector and then use this vector for other operations. This program shows how to read from a text file into vectors.

The input file is as follows:

Line num 1

Another line

Line number 3

4th Line!

**%** Last line **%**

Program as follows:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace
std;

int
main()
{

vector<std::string> lines;
lines.reserve(5000); //Assuming that the file to read can have max 5K lines

string fileName("test.txt");

ifstream file;
file.open(fileName.c_str());

if
(!file.is_open())
{

cerr<<"Error opening file : "<<fileName.c_str()<<endl;
return
-1;
}


//Read the lines and store it in the vector
string line;
while
(getline(file,line))
{

lines.push_back(line);
}


file.close();

//Dump all the lines in output
for(unsigned int i = 0; i < lines.size(); i++)
{

cout<<i<<". "<<lines[i]<<endl;
}


return
0;
}




Output as follows:

Tuesday, 8 March 2011

Switch Case using string

When I started thinking of this example, I also faced some of the other problems that I have encountered in my initial days of C++. One of these problems was how to convert String to multiple Ints and how to split strings easily, etc. Hopefully you will find the example useful.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>
#include<sstream>
#include<map>

using namespace
std;

void
split(const string& input, int& num1, int& num2, string& operation);
int
calculate(int num1, int num2, string operation);

int
main()
{

string s[5] = {"2 + 2", "4 - 1", "4 * 6", "18 / 3", "12 ^ 2"};

for
(int i = 0; i < 5 ; i++)
{

int
num1=0, num2=0;
string op;
split(s[i], num1, num2, op);
int
retVal = calculate(num1, num2, op);
cout<<s[i]<<" = "<<retVal<<endl;
}


return
0;
}


void
split(const string& input, int& num1, int& num2, string& operation)
{

istringstream iss(input);
iss >> num1;
iss >> operation;
iss >> num2;
}


int
calculate(int num1, int num2, string operation)
{

enum
Operators {unknown, add, sub, mul, div};
map<string, Operators> mapOfOperators;
mapOfOperators["+"] = add;
mapOfOperators["-"] = sub;
mapOfOperators["*"] = mul;
mapOfOperators["/"] = div;

switch
(mapOfOperators[operation])
{

case
add:
return
num1 + num2;
case
sub:
return
num1 - num2;
case
mul:
return
num1 * num2;
case
div:
return
num1 / num2;
default
:
cout<<"Unrecognised Operator "<<operation<<endl;
}

return
0;
}


The output is as follows:
See Also: Codeguru article on 'Switch on Strings in C++'.

Friday, 4 March 2011

Removing all white-spaces from a string

Continuing on the same theme as the last post. What if all the spaces need to be stripped out from the input string:



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#include<string>

using namespace
std;

string removeAllSpaces(const string& s)
{

string newStr(s);
bool
spacesLeft = true;

while
(spacesLeft)
{

int
pos = newStr.find(" ");
if
(pos != string::npos)
{

newStr.erase(pos, 1);
}

else

spacesLeft = false;
}


return
newStr;
}


int
main()
{

string aString("This string has multiple spaces problem!");

cout<<"Original : "<<aString<<endl;
cout<<"Modified : "<<removeAllSpaces(aString)<<endl;

return
0;
}





The output is as follows: