Laiq Ahmed 42 Junior Poster

After carefully checking the Anciant dragons comments I checked again, and Find that, It works as it should when the following is used.

nth_element (arr.begin (), arr.end()-1, arr.end (), less<int>());

Check to see if it really works.
and tell me why you use the less_equal ?

Laiq Ahmed 42 Junior Poster

I have analysed your code and finds that the nth_element works as it should, I tested it on VC++ 2005 and VC++ 2008.
After changing the code you suggested

for ( long i = 1 ; i <= 1 ; i++ ) {	
		
		generate	( arr.begin(), arr.end(), myIntegerRand );
		
		start 	 = arr.begin();
		end	= arr.end();            // to point to the last element
		
		int pivotValue = *(end-1);	// pivot being the last element in the present Array
		
		cout << "\n\n Array before Partitioning" ; 
		printf ("(%d) -> ", distance (start, end) ) ;
		copy ( start, end, ostream_iterator <long> (cout, " ,") );
		cout <<  " \n Pivot chosen is " << pivotValue ;
		
		nth_element (start, end-1, end, less_equal <int> ());
    	
		 cout << "\n Partitioning Done Array is now -> " ;
		copy ( start, end, ostream_iterator <long> (cout, " ,") );
		cout <<  " \n Remember Pivot chosen was " << pivotValue ;

	}

it still works fine, I think you are doing some mistak while doing some iterator arithmatic.
[bold]end () points to one past last element not the last element.[/bold]
Explain if its not your problem.

Laiq Ahmed 42 Junior Poster

I don't know about what your TreeNode do ? what are its members.
one problem that is visible is that, you have 1000 data elements,
but you have just created only 2 nodes out the loop what about other 998 nodes...you are not allocating the space for them

your code.

for (int p=0; p<1000; ++p)
if (Root == 0)
{
   Root = new TreeNode();
   Root->val = C;
 }
else 
{
   TreeNode* temp = Root;
   while (temp)
   {
	if (edit(B,C)<r)
	{
	   if (temp->LChild)
	      temp = temp->LChild;
	   else 
	   {
                      TreeNode* t = new TreeNode();
                      t->val = B;
	      temp->LChild = t;
	      break;
	   }
	}

	if (edit(B,C)>=r)
	{
	   if (temp->RChild)
	       temp = temp->RChild;
	   else 
	   {
                       TreeNode* t = new TreeNode();
                       t->val = B;
	       temp->RChild = t;
	       break;
	   }
	}
   }
}

Hope this helps.

Laiq Ahmed 42 Junior Poster

set the prototype of functions
like this

void setW();
void setL();

replace above two with

void setW(double num1)
void setL(double num2)

remember to add semicolon where required.

Laiq Ahmed 42 Junior Poster

any time, But I have left one small bug in the above algorithm for the sharp eyes, please check that also. nothing is a free cake :). small efforts required.

Laiq Ahmed 42 Junior Poster

Tell me how good you are with C/C++, and one more thing what your above program does.

Laiq Ahmed 42 Junior Poster

Deleting a node is not difficult.
let me tell you the algorithm.

Algorithm.
Delete (value)
1. Check if head is null return
2. if the value matches head
set temp = head
set head = head->next
free head.

3. Link previous = head;
4. Link temp = head->next;

5. while (temp->data != value)
do
temp = temp->next
previous = previous->next

6. if temp is not null
set previous->next = temp->next
free temp.

Hope this helps

Laiq Ahmed 42 Junior Poster

why don't you traverse the array
and check if the value is non zero add them,

// traverse the array.
    if ( a[i] != 0)
               sum += a[i];

// after loop
cout<< sum;

this is what i understand from your description.

Laiq Ahmed 42 Junior Poster

dougy83
thanks, I know this is the portable and most suitable way to swap, there exists several other swapping techniques, but I was concentrating on technique adopted by Yellowdog428. I want him to find out this technique himself.

Thanks anyway.

Laiq Ahmed 42 Junior Poster

Agreed, Anciant Dragon.

Regards,
Laiq

Laiq Ahmed 42 Junior Poster

writting a better code is not difficult until and unless you think that you will not avoid the things you know and well understand the problem.

first of all this is not an OOP.
if you are willing to write OO Program you should think in terms of objects and their relationship.

lets optimize your code.

char something[256];
char text[256];
char text1[256];
char filetext[256];
char filename[256];
string line;
string write1 = "write";
string open1 = "open";

1) always declare the variable near the point where they should be used.
making all the variable global doesn't make sense.
2) make variable constant if they will not change through out the program life. don't use obscure name like write1 or open1.

const string WRITE = "write";

3. Don't use "\n" rather than use std::endl ? why search about it. what if you compile where newline is is defined as "\r\n"
4. Magic Numbers problem as mentioned by Anciant Dragon.

5. check if the stream is_open(..).

6. make proper functions to do read and write.

Hope this helps.

Laiq Ahmed 42 Junior Poster

your link list implementation is stack based implementation,
to reverse it you first need to know how to reverse the list.

there are three ways of doing this.
1. Recursive.
2. using explicity stack.
3. using iterative approach. ( the one you are using).

your code says the following

node* reverse_list(node* head_ptr){	
               cout << "Reversed..." << endl;
 	node* result_ptr = NULL;
	node* curr_ptr = NULL;
	while (head_ptr)
	{
		curr_ptr = head_ptr;
		head_ptr = head_ptr->link( );
		curr_ptr->set_link(result_ptr);
		result_ptr = curr_ptr;
	}
	return result_ptr;
}

what it does.
statement 1. do nothing but printing.
you got two extra pointers.
traversing the list on the basis of headPtr.
holding the headPtr in currentPtr.
incrementing the headPtr.
setting NULL in the currentPtr link.
setting resultPtr = CurrentPtr ( which is same as headPtr ).

this was your first iteration. but where you reversed the list.

always remember to check the preconditions and postconditions.
in the reverse case the precondition is to check if the list is null, or it contains only one element. reversing that would be nothing ...

lets do the reverse.

void Reverse (Link* head)
{
	//checking preconditions.
	if (!head && !head->next)
	          return;
                //here we are sure that second node exists.
	Link* temp = head->next; // holding 2nd node reference.
                Link* iter = temp->next; // hold the reference of 3rd Node OR NULL.
	head->next = 0;  // setting the first Node next = …
Laiq Ahmed 42 Junior Poster

Lets do some binary Tree.
What your algorithm says.

I pick a pivot p from a database S of strings, compute the median r of the distances of the string objects to p and then divide the objects into roughly equal-sized subsets S1 and S2 as follows:
S1={o ε S \{p}|d(p,o)<r} and
S2={o ε S \ {p}|d(p,o)>=r}
where d(p,o) is the distance of the database object o to pivot p.Thus, the objects in S1 are inside the ball of radius r around p, while the objects in S2 are outside this ball.

first analyze your problem in detail.
how to find a pivot is the first question that rings in my mind, if I find the pivot by dividing the entire database S of strings by 2. that means I should know the bounds. m i right of lets forget about dividing it by 2, next what we need to do if we are choosing random pivot, what if it goes out of bounds ? you are doing the right thing by taking modulo N.
Then we need to calculate the median. you can use simply formula over the vector indices to calculate the median.

now what you need to do is to calculate the distances of pivot from each element in the string database S. and store them in some collection if you know vector use vector instead of plain arrays.

okey lets come to binary tree.
What your edit …

Laiq Ahmed 42 Junior Poster

Lets do some sorting.

First of all the sorting technique you are using is sort by swapping. famous as a bubble sort.
before sorting lets improve your code. which is more strutured

Why are you keeping the two related things separate? why don't keep these two things rainfall & month as an aggregate. here comes structure.

struct RainFallInfo { 
     double rainFall;         // stores information about rain
     char month[10];       // stores information about month.
};

how to sort this.
is simple

void Swap (RainFallInfo& first, RainFallInfo& second)
{
		// swapping technique...
		RainFallInfo temp;
		temp.rainFall = first.rainFall;
		strcpy (temp.month, first.month);

		first.rainFall = second.rainFall;
		strcpy (first.month, second.month);

		
		second.rainFall = temp.rainFall;
		strcpy (second.month, temp.month);
}


void Sort (RainFallInfo rInfo[], int MONTHS)
{
	for (int i=0; i<MONTHS; ++i)
	{
		for (int j=i+1; j<MONTHS; ++j)
		{
			if (rInfo[i].rainFall> rInfo[j].rainFall)
			{
					Swap(rInfo[i], rInfo[j]);
			}
		}
	}
}

Hope you understand.

where you lack can be seen by comparing my sort function with yours.
like these.

startIndex < (MONTHS - 1); // should be replaced by MONTHS

strcpy is required to copy char array to other char array.
Hope this helps...

if you don't know references, 'RainFallInfo&' you can replace this by RainFallInfo* and do the same.

Laiq Ahmed 42 Junior Poster

one thing,
return 0 from main not 'o' (not o)
your code will work

try this

j = rand()%50;

and replace your condition

if (!(j >= 50&&j<=0))
cout<< j<<endl; 
else
cout<<"out of range"<<endl;

and only print the j
what is does ? requires minute mathematics.

Laiq Ahmed 42 Junior Poster

make sure you understand the anciant dragon's post completely :).

your algorithm doesn't do the right thing in reading

it should read after opening file directly
remove your first read call

one more thing return the vector<>& from readFile function
replace the file.read (...) , problem lies there.
you will solve it

Laiq Ahmed 42 Junior Poster

what it actually does.
Let me tell you what it actually does, and what it should do
first what it does

template <class T>
void myVector<T>::grow(){    
   while(size >= capacity)    {        
        T* temp;        
        temp = data;         
        capacity *= 2;         
        data = new T[capacity];         
        for(int i = 0; i < size; i++)        
        {
             data[i] = temp.data[i];        
        }
         delete []temp;    
  }
}

basically T refers to int in your case now the new code becomes.

void myVector<int>::grow(){    
   while(size >= capacity)    {        
        int* temp;        
        temp = data;         
        capacity *= 2;         
        data = new int[capacity];         
        for(int i = 0; i < size; i++)        
        {
             data[i] = temp.data[i];        
        }
         delete []temp;    
  }
}

lets move from bottom up manner you'll recognise yourself.
what does your sentence data = temp.data means ???
int is a primitive type not a aggregate type, so a compile error is there.
now you know what should be change.

Laiq Ahmed 42 Junior Poster

also don't forget to remove or comment this code

infile.close();
   infile.open("file");
//   exit(1);      
   mergeSort(allInfo, 0, n-1);

change the reading code as well. it doesn't include the last record in the collection does it ?

while (!infile.eof())
   {
      currentStudent = new Students(social, firstName, lastName, gpa);
      allInfo[n] = currentStudent;
      n++;
      infile >> social >> firstName >> lastName >> gpa;
   }

check what happen on last iteration. it reads the data from stream but will not make the student record from data read.

Laiq Ahmed 42 Junior Poster

Just pass n-1 as the last argument to mergesort function

Laiq Ahmed 42 Junior Poster

_cdecl and _stdcall has some difference, I think you are calling the function from the library written using different calling convention than the one you are using. Its basically a name decoration issue, not resolved by linkers.

In VC++ 6.0 _cdecl is the default calling convention.

_cdecl In this type convention the caller is responsible for cleaning up the stack.
_stdcall In this type of convention the callee is responsible for cleaning up the stack.

search calling conventions.

Ancient Dragon commented: Thanks for the correction. +25
Laiq Ahmed 42 Junior Poster

Can any1 tell me about the tutorials and description regarding new c++ standard. specially the improvement in STL.

Laiq Ahmed 42 Junior Poster

Can anyboby help me i really dont get the feeling of big o notation, i just want to understand it.

Big O Notation is used to denote the complexity of the algorithm ( worst case complexity)...

for example
the following code has complexity O(n)

for(int i=1;i<=n; ++i ) 
{
   // do something... (atomic statements ).
}
Laiq Ahmed 42 Junior Poster

You're making a series of nested boxes. The reason you failed is because you're trying to do it all at once, probably with no prior experience solving this kind of problem. So what you need to do is simplify it down to something that you can solve. For example, create a single filled box:

N: 4
 
1111111
1111111
1111111
1111111
1111111
1111111
1111111

Now draw it empty:

N: 4
 
1111111
1     1
1     1
1     1
1     1
1     1
1111111

The key element is that N designates a cross down the center of the box:

111*111
111*111
111*111
*******
111*111
111*111
111*111

You count up to N and then back down to 0. Once you understand and can implement all of this, try looking for patterns between the first row/column and the central row/column. That's where you come up with the final parts of the algorithm.

And no, I'm not going to tell you how to do it. It's important that you work through the process on your own. However, I can and will offer hints after you make some kind of attempt and show us your results.

Thank you for such a nice description... friend i come up with a solution with a difference logic but still thank you for your help...

//******************** for n=2;
/* 1 1 1
1 2 1
1 1 1 
*/
/********************* for n=3 ******************
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1 …
Laiq Ahmed 42 Junior Poster

I want to generate the following pattern using for() loop only.... how can i do this i've tried but unfortunately failed to solve ....

when user inputs 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

when user inputs 4;

1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 1 1 1 1 1 1

I just want to know the algorithm or just a hint?

sorry my Mistake it goes like this

1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1

Laiq Ahmed 42 Junior Poster

I want to generate the following pattern using for() loop only.... how can i do this i've tried but unfortunately failed to solve ....

when user inputs 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1

when user inputs 4;

1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 1 1 1 1 1 1

I just want to know the algorithm or just a hint?

Laiq Ahmed 42 Junior Poster

access c++ private data members without using the " Friend" type
main() can be a friend function?

its against OOP concept but still... this might help

class A { 
private:
int a;
char b;
public:
A(): a(1), b('A') {}
};
int main() 
{
A* obj = new A();;
int* pInt = reinterpret_cast<int*>(obj);
cout<<*pInt<<endl;
++pInt;
cout<< *reinterpret_cast<char*>(pInt) <<std::endl;

}
Laiq Ahmed 42 Junior Poster

as above.

string s;
cin >> s;

for example, if the user enters Orange, i want it to convert to orange.
please advise what i should do.


thanks in advance

Check out this code

std::string str;
cin>>str;
transform(str.begin(), str.end(),str.begin(), tolower );
cout<< str;
Laiq Ahmed 42 Junior Poster

Thank You ~S.o.S~ & Ancient Dragon for your help finally i learn how to calculate the polynomial complexity.....

for( int i=0; i<n; ++i )
    for( int j=0; j<i; ++j )
         printf("Hello World");

if we consider the inner loop the complexity ...

In the above loop int i=0; is an atomic statement which executes O(1) time i.e. constant time.
i<n executes (n+1) times
++i executes (n+1) times

printf(“Hello World”); //executes n times

so the total complexity is 1 + (n+1) + (n+1) + n = 3n+3

and the complexity of the ourter loop would be ...
For(int i=0; i < n; ++i )
{
//something executes 3n+3 times………….
}
lets examine the outer loop,

int i=0; //executes 1 time
i < n; //executes n+1 times\
++i //executes n+1 times.
And last the body executes ?? interesting………….
See………….
First i=0;
Complexity of body is 3(0)+3
i=1
Complexity of body is 3(1)+3
i=2
Complexity of body is 3(2)+3
i=3
Complexity of body is 3(4)+3
………………………………
……………………………….
i=n
Complexity of body is 3(n)+3

Therefore, total complexity is equal to

1 + (n+1) + (n+1) + [ {3(0)+3} + {3(1) + 3} + ………… + { 3(n) + 3} ]..
1 + (n+1) + (n+!) + [3(0 + 1 + 2 + 3 + … + n) + 3n] //using 1 + 2 …

Laiq Ahmed 42 Junior Poster

i want to calculate the complexity of the following code snippet

for(int k=0;k<n; ++k)
    for(int j=0; j<k; ++j)
        for(int i=0; i<j; ++i)
                cout<< "Hello World" <<endl;

here! i got the hint! that summation of natural numbers series would be used if its correct why ?
bit confused:sad:

Laiq Ahmed 42 Junior Poster

heyz it its undefined what about the following code

class  A { 
  int a;
public:
  A() : a ( 0 )  {}
 
 int get() const {
       cout <<" in A()" << endl;
       return a; 
 }
};
 
int main()
{
       *((int*)0x00100ff)=14;
       cout<< reinterpret_cast<A*>(0x00100ff)->get() << endl;
       return 0;
}

it works ..........:)

Laiq Ahmed 42 Junior Poster

please help me understand the folowing code....

class A {
      int a;
  public:
     A() : a ( 0 ) {} 
     int get()  {
          cout << "Hello WOrld " << endl;
          return 0;
     }
 };
 
  int main( int argc, char** argv )
 {
      cout<< ((A*)3)->get() << endl;
       return 0;
 }

this code runs! and prints the correct output if i return zero in get() function,, but when i return a it throws an exception ( i think becuase a is not initialized, infact not constructed ), but this code runs ......no idea:eek:

Laiq Ahmed 42 Junior Poster

You can get the effect of Virtual Constructor by using Factory design pattern...... which doesn't violates the objected oriented rules specifically inheritance structure........ but its helpful. and some times needed....

The vptr not necessarily initialized by the compiler in the constructor it might be initialized during the construction... its totally the implementation dependent thing... i.e. to preserve the polymorphic behavior. Some compiler might not use Vptr and vTable to hold the virtual functions entries..... they might use some other structure to behave polymorphically.......

check out http://www.daniweb.com/techtalkforums/thread18399.html.
get some idea about virutal constructor kind stuff.
Hope you get the basic idea..

Laiq Ahmed 42 Junior Poster

The problem you've described might consists of pair of key value... using pair< T1,T2> template is agood choice .....then.

I totally agree with salem, every Data Structure has some advantages and tradsoff, its depends upon your need and how it fits the scenario...

in LIFO(Last in First Out) link list the complexity of insert is O(1);
search is O(n) and it provides the forward iterator;.......

in most situation with pair of values we often need to change the "value" part of pair with key like v["key"]="value";
this is often required what is called Random Access iterator like array indexing mechanism.....

I suggest you to develop your Own std::map like structure and modify it that best suited your needs........

Laiq Ahmed 42 Junior Poster

This is the first time i found such code to read from the ostream.......
i can just help you with the syntax i m also trying to code this... soon i'll conquer or will give up..... :d.

class PhoneNumber {
   string area_;
   string exchange_;
   string line_;
public:

   PhoneNumber(string const& line,string const& exchange,string const& area);
   istream& operator<<(ostream& os);
   friend bool operator<<(string& str,PhoneNumber const& Value);
   friend ostream& operator<<(ostream& os,PhoneNumber const& Value);

};
 
PhoneNumber::PhoneNumber(string const& line,string const& exchange,string const& area):area_(area),exchange_(exchange),line_(line){}
 
bool operator<<(string& str,PhoneNumber const& Value)
{
   str+="(" + Value.area_ + ")";
   str+=" " + Value.exchange_;
   str+="-" + Value.line_;
return 0;
}
ostream& operator<<(ostream& os,PhoneNumber const& Value)
{
   return os<<"("<<Value.area_<<")"<<" "<<Value.exchange_<<"-"<<Value.line_;
}
istream& PhoneNumber::operator <<(ostream& os)
{
   //still to code

}

If you solve this please let me know i've tried using istream_iterator but couldn't find any result.....

Laiq Ahmed 42 Junior Poster

iamthewee sorry~! for incomplate description... basically i m developing a psuedo compiler.. i need every word (i.e. lexemes)..

Micko Your Code is almost the same i was thinking about may be our minds resembles :d..... just kidding....

but the problem is that you are using getline(any_string_stream, string_Buffer); this causes the basic_io operations to be done more than once, instead we can do better than that i.e. we can just read the entire stream in the string and then process which might result in faster one............................ Do you agree....
although The data strcuture you are using and i am using are the same :d.... map & vector; :).

by the Way thanks...........
I'll Post my Code tomorrow regarding this.....but before that i want to write the optimum code....
can do better i know :).. with your help/discussion

Laiq Ahmed 42 Junior Poster

I m Reading a sourc program and separating the Words in the source program i need a structure to hold the information about those words with respect to their line numbers

for example

int a;
int main() 
{
       return 0;
}

i need a data structure that will allow me to store information about the words.......
say,
Words Line Numbers
int 1
a 1
int 2
main 2
( 2
etc...

Laiq Ahmed 42 Junior Poster

I want to read a Source Code file and separate the lexemes (words) and want to track the line number with the separated words?
I just come up with the raw code like that...
i) A struct holding a string , int pair;
ii) making the link list of above struct

for example

class Container {
 
   struct Words{ 
      string word;
      int lineNo;
};
//
vector<Words> vWord;
int& operator[](string const& Value);  //use to get the line number corresponds to given value;
};

please tell me is there any optimal solution than this.........

Laiq Ahmed 42 Junior Poster

I've just tried to code the Binder2nd, almost same as standard code provided in functional...... please point out the mistakes........ and suggest me guidelines to write effective code..........

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>
 
using namespace std;

 
template <class _Fn> 
class Binder2: public unary_function
  <typename _Fn::first_argument_type,
                typename _Fn::result_type> 
{
protected:
typedef typename  _Fn::second_argument_type sArg_;
sArg_& secArg_;
 _Fn& fn_;
public:
Binder2(_Fn const& fn,typename _Fn::second_argument_type const& sArg)
:fn_(fn),secArg_(sArg){}
typename _Fn::result_type operator()(typename _Fn::first_argument_type& arg)
{
return fn_(arg,secArg_);
}
};
template<class _Fn,class _Arg> 
inline Binder2<_Fn> bind_(_Fn const& fn,_Arg const& arg)
{
return Binder2<_Fn>(fn,arg);
}
int main()
{
std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
//this should print 5 10 15 20 25...... don't know why :S
std::transform(v.begin(),v.end(),v.begin(),std::ostream_iterator<int>(cout," "),bind_(std::multiplies<int>(), 5));
cout<<"\n";

cin.get();
 
return 0;
}

Help me in finding the error...... the error is @

bind_(std::multiplies<int>(),5)

term doesn't evaluate to a funciton taking 2 arguments :S

Laiq Ahmed 42 Junior Poster

Amazing Article :). Thanks from my side :).

Laiq Ahmed 42 Junior Poster

I can just explain you how to code on code it in any language of your desire

Algorithm Suggest: -
i) visit the left Subtree
ii) visit the Node
iii) visit the right Subtree

You are interested in making the Non Recursive version of the above traversal. You can make it easily... if you know how recursion attempts the problem, infact recusion is using the implicit stack. So you might use an explicit stack to tackle the same problem :). My Suggessions are first try to solve it by hand then you'll get the idea what infact you are doing then try to code the logic.
Give me your code of recursive Version I'll give you mine (non recursive version :d).......

Hope you get the basic idea........

Laiq Ahmed 42 Junior Poster

What is the Importance and uses of data stuctures in Programming using C/C++ when using it?


I think data storage and retrieval + usage of memory effeciently etc are the concepts that are the basis of Data Structure,...
answer my Few Question: -

In a drawing software can you tell me how many shapes are needed ?

In a Account Management System how many account holder your program can handle ?

this leads to the memory management, people often answer that they would utilize the heap to solve such problems....okey fine you utilizes the heap. now let talk about the retrieval of data...... infact you need the dynamic linkage between account holder to go forth and back...........how would you implement search! i.e. how can you figure out the specific account holder..... there are several problems which directly maps to the data structures....

Array is also a data structure , that provides you with Random Iterator :) . i.e. you can get anywhere within the bounds by indexing....why you need arrays:D. Again if you don't know how many of ints you need ? what you will do ? you'll either create a list or vector(similar to arrays).....................

Data structure not only stores information in a decent way but also provide the decent retrieval interface required by the problem... list, queues, stacks are linear structures you can think beyond that, Associative Structures.... maps in C++.

HOW STACK, QUEUES and list works
The …

Laiq Ahmed 42 Junior Poster

I've gone through several books they explain Upcasting as
Base class pointer pointing to Drived class Object

this definition is correct.
Downcasting:

Drived class pointer pointing to base class object..

i got a bit confused.....not having crystal clear image in my mind.....
if the above definition is correct... whats wrong with the below code

class Shape {
public:
   virtual ~Shape() {}
};
class Circle: public Shape {
public: 
   ~Circle() {} 
};
 
int main() 
{
      //why this can't work ...........according to definition....
    //  Circle* c = dynamic_cast<Shape*>(new Shape);
 
     //why this
     Shape* s = new Shape;
     Circle* c = dynamic_cast<Circle*>(s);
     return 0;
}

I know that downcasting is performed between polymorphic types :) . I m bit confused with its definition and implementation... please give me the solid concept ;) .

Laiq Ahmed 42 Junior Poster

Sorry for late replying! was busy! hmmmZ. sending you a snippet of code that might help you :). concentrate on the technique of reading and writing to file you can Edit any record ~!.Check the technique of Record Number that is included. now Code the delete function yourself :). Hope you get the basic idea :)

#include <cstdio>
struct CData; //declaration
void Add(CData* val);
void Edit(CData* val,int rec_no);
void Read_CData(CData*);
void Print_CData(CData*);
FILE* fp; 
struct CData {
int iRecNo; //holds the record number;
char Cust_Name[20]; //holds the name only 
};
void Init() 
{
if((fp = fopen("c:\\laiq.txt","a+r"))==0)
{
printf("Error");
exit(0);
}
else
printf("File is opened SuccessFully\n");
}
void ShutDown()
{
fclose(fp);
}
void Add(CData* data)
{
//read the data from Console
if(!fp)
Init();

Read_CData(data);
fseek(fp,0,SEEK_END);
fwrite(data,sizeof(*data),1,fp);

}
void Edit(CData* val,int rec_no)
{
fseek(fp,(rec_no-1)*sizeof(*val),SEEK_SET);
fread(val,sizeof(*val),1,fp);
Print_CData(val);
}
int get_Rec(){
static int rec_no;
return rec_no++;
}
void Read_CData(CData* val)
{ 
val->iRecNo=get_Rec();
printf("\nEnter the Customer Name: ");
gets(val->Cust_Name);
}
void Print_CData(CData* val)
{
if(val){
printf("Record Number: %d\n",((val->iRecNo)+1));
printf("Customer Name is: %s",val->Cust_Name);
}
else 
printf("Nothing to print :P");
}
int main()
{
CData value; //value is used for adding records :).
Init();
Add(&value);
Add(&value);
Add(&value);
CData val; //holds the record for editing :)
Edit(&val,2); 
ShutDown();

return 0;
}

still having problem then use the MSDN Library :) for File Pointer

Laiq Ahmed 42 Junior Poster

The stack is a lifo(last in first out) based sequential structure. I think you don't need a double link list to implment it, you can implement lifo based list directly.

struct Node {
  int m_iVal;
  Node* m_pNext;
  Node(int const& iVal,m_pNext=0)
}

if you've used the stack it provides three basic as well as standard functionality
push() to push the element on the top of stack
pop() to pop the element from the top
top() returns the top element;
there is no need for display function in the standard stack.
if you need that function
you should have written like that

void display() 
{
//it uses 
while(HEAD) 
{ 
   while(HEAD) 
    {
        cout<<HEAD->top()<<endl;
        HEAD->pop();
     }
}

Your push function takes the pointer as an argument there is no need for that, and remove the friend from there.......
push should be member function.~! i.e. void push(int value) remember this pointer is always passed quitely to member function so no need to pass explicity and declare it as a friend and you are violating the OOP concept encapsulation by doing this.why you've used static counter.............if you declare push as a member function there is no need for that. also why don't you utilize HEAD variable for this.
your push function should be like this.

void push(int value)
{
HEAD= new Node(value,HEAD);
//or its also fine
/* if(HEAD==0)
HEAD= new Node(value);
else {
Node* temp = new Node(value)
temp->m_pNext=HEAD;
HEAD=temp;
}*/
 
}

you didn't include …

Laiq Ahmed 42 Junior Poster

Swapping two variables is an easy stuff if you are using temporary variable

void swap(int& a,int& b)
{
     int temp=a;
               a=b;
               b=temp;
}
 
 
//in C++ template
template<typename _Type> 
void swap(_Type& t, _Type& t2)
{
   _Type temp=t;
           t=t2;
           t2=temp;
}

using only the two variables requires a little maths.
check that out it might work for ints.

void swap(int& a,int& b)
{
    a=a+b;
    b=a-b;
    a=a-b;
}

Hope you got the basic idea........... try it out.....
The XOR algorithm is another choice and probably good one ...........and its simple check that out urself. remember (A ^ B) ^ B=A :)

Laiq Ahmed 42 Junior Poster

Pointer to function are the pointers which have the ability to call the function pointed to by them.As the ordinary pointers take the address of variable and can change the value pointed by them, the function pointer almost does the same.

#include <iostream>
#include <string>
 
using std::string;
using std::cout;
 
//simple function
void print(string _name) { std::cout<<"Hello"<<_name; }
 
//another function with return type int.
int cal_pay(double _pay,int _hours) 
{
    return (2*_pay + 1000)*_hours;
}
 
//function pointer of the same type i.e. complete function type must match exactly
void (*pfct)(string);   //check the return type and arguments   
int (*cfct)(double,int);
int main() 
{
     pfct=&print;             //pfct points to print function
     pfct("Laiq");
     
     cfct=cal_pay            //also o.k. same as &cal_pay
     int ans = (*cfct)(500.00,4);    //another way of calling 
     return 0;
}

you can use typedef to clean declaration
typedef void (*pfct)(string);
void say(string);
void no(string);
void yes(string);
pfct my[] = { &say, &no, &yes };

also you can use the pointer to function in function's argument to specifify the details... like comparision criteria in sort funciton ;

typedef int (*Comfct)(MyType const*, MyType const*);
void sort(vector<MyType>& v,size_t n, Comfct Cmp);

Hope you got the basic idea..............

Laiq Ahmed 42 Junior Poster

Editing is a trick in File based databases.........you can use several ways to achieve this....

1. Use the array of Structure and read the entire file in array of structure.......... and do all the work with that array and write the array back to the file........................ its not effecient. as your size increases. You may get some problems.

2. you can use fseek() function..................
here is an example of using fseek to get the desired record.
int fseek(FILE* stream, long offset, int origin)
Now, your structure size is around 317 bytes. now to get nth record you can use
fseek(file_ptr, ((n-1)*sizeof(entry)),SEEK_SET);


Now to update the file you can either use r+, a+ or w+.
if you need a string that are separated by whitespace (i.e. Space) then you should use a string array or char** or array of char*.

"scanf() terminates on \n". I havent seen any example of using \n in scanf() :).
Try to read the entire structure using fread(&entry,sizeof(entry),1,file_ptr);
I think this would help you out........:confused:

Laiq Ahmed 42 Junior Poster

Inheritance simply means Reusing the Interface of the base class. Two classes have something in common for example consider the following example. There are two classess Shape(a base/parent class) and Circle(a derived/child class ) you might have guessed there is some relationship between shape and Circle. Every shape has color including circle. So if we make the interface of the shape and inherit the interface of the shape class to circle we just need to mention the information specific to Circle

class Shape {
public:
void draw();
void fill_color();

};

//inheritance syntax
class Shape: public Shape {
public:
void Set_radius();
private:
size_t radius;
};

This is the simplest information i can provide hope you got the basic idea....:confused: