Laiq Ahmed 42 Junior Poster

I would recommend reading the following thread for detailed explanation on why cin is better to be used in while loop.

http://www.parashift.com/c++-faq-lite/input-output.html
[15.2] Why does my program go into an infinite loop when someone enters an invalid input character?

another thing if you want to break on the size of array.. why don't you use. the for loop?

for (int i=0; i<10; ++i)
{
   cin >> c;
   a[i] = c;
}
Laiq Ahmed 42 Junior Poster

Hi,
your question is bit unclear... what are you storing in the multimap logically. What I've understood is that you want to get the multiple values against the same key

multimap<int, string>  mm;
	mm.insert(std::make_pair(1, "a"));
	mm.insert(std::make_pair(1, "c"));
	mm.insert(std::make_pair(2, "d"));
	mm.insert(std::make_pair(2, "e"));

	typedef pair<multimap<int, string>::iterator, multimap<int, string>::iterator>  Pair_Range;
	Pair_Range  pRange = mm.equal_range(1);
	
	for (multimap<int, string>::iterator it = pRange.first; it != pRange.second; ++it) {
		cout << it->second<<endl;
	}

Hope this helps

iamthwee commented: no -4
Laiq Ahmed 42 Junior Poster

search Longest Common Subsequence algorithm. and modify that algorithm to meet your need.

Laiq Ahmed 42 Junior Poster

when I was learning this topic. I followed the very good series of articles on code project, check the below link

http://www.codeproject.com/KB/atl/atl_underthehood_.aspx

Hope above helps.

Laiq Ahmed 42 Junior Poster

Thank you mcco for providing me the definition of RECT structure

kindly provide me the values (numbers), It seems that your expression evaluates to zero thats why I've asked to provide me the values not the RECT members. :).

Laiq Ahmed 42 Junior Poster

What are the values of RECT members?

Laiq Ahmed 42 Junior Poster

hmmmmmmmmmm, I've come up with some solution to you problem hope this might help you.

class ICommand {
public:
	virtual ~ICommand() = 0  { }
	virtual void ExecuteCallBack(int iCommandId) = 0;
};

// Command Base Object.
template<class T>
class Command : public ICommand {
	typedef void (T::*Delegate)(int a);
	vector<Delegate> memFunctions;
public:
	Command() { }
	void RegisterCallBack(Delegate func) {
		memFunctions.push_back(func);
	}

	Delegate GetCallBack(int idx) { 
		// add checking of constraint.
		return memFunctions[idx];
	}

	// you can add functions like 
	// void executeAllCallBacks() = 0;
	virtual void ExecuteCallBack(int iCommandId) = 0;

};


class Administrator : public Command<Administrator> {
protected:

	virtual void ExecuteCallBack(int iCommandId) {
		(this->*GetCallBack(iCommandId))(8);
	}

	Administrator() { }
public:
	
	

	void Add(int a) {
		cout << "Administrator Add"<<endl;
	}

	void Remove(int a ) {
		cout << "Administrator Remove"<<endl;
	}

	static Command<Administrator>* GetInstance() {
		return new Administrator;
	}
};


class HR : public Command<HR>  {
protected:
	virtual void ExecuteCallBack(int iCommandId) {
		(this->*GetCallBack(iCommandId))(8);
	}
HR() { }
public:
	
	void Add(int a) {
		cout << "HR Add"<<endl;
	}

	void Remove(int a ) {
		cout << "HR Remove"<<endl;
	}

	static Command<HR>* GetInstance() {
		return new HR;
	}
};




int main ()
{
	Command<Administrator>* obj = Administrator::GetInstance();
	obj->RegisterCallBack(&Administrator::Add);
	obj->ExecuteCallBack(0);

	Command<HR>* obj2 = HR::GetInstance();
	obj2->RegisterCallBack(&HR::Add);
	obj2->ExecuteCallBack(0);

	// now the interesting Part.
	vector<ICommand*> vec;
	vec.push_back(obj);
	vec.push_back(obj2);

	for(size_t i=0; i<vec.size(); ++i) {
		vec[i]->ExecuteCallBack(0);
	}

	return 0;
}

Hope this help, you can further comment on this as well.

Laiq Ahmed 42 Junior Poster

bool, true, false are already keyword in C++. you don't need to define enum for it.

Laiq Ahmed 42 Junior Poster

Hi FirstPerson,

I've tweaked your code to meet your needs, I think you are trying to acheive something like this.

class Tetris {
public:
	bool DrawLine(unsigned int iColId) {
		cout << "Draw Line of Tetris"<<endl;
		return true;
	}
};

template<typename Type>
class vec2D
{
	
	typedef bool (Tetris::*MFPtr)(unsigned int ID);
	MFPtr mydrawFuncPtr;

private:
	unsigned int Col_id;
public:
	Type x;
	Type y;	

	vec2D(Type x0,Type y0) : x(x0), y(y0) { }
	vec2D() : x(0),y(0){ mydrawFuncPtr = 0; }

	void reset() { x  = 0; y = 0; }

	//Enables each object member to have its own unique draw func. 
	void setDrawFunc(MFPtr drawFunc  ) {  mydrawFuncPtr = drawFunc;}


	//get-set methods
	unsigned int Color() { return Col_id;}

	void Color(int i) { if(i < 0) Col_id = 0; else Col_id = i; }

	// WRONG.
	//void drawShape(vec2D<Type>& obj,unsigned int colID) 
	
	//CORRECTED:
	void drawShape(Tetris& obj,unsigned int colID) 
	{		
		(obj.*mydrawFuncPtr)(colID);
	}
};

int main ()
{

	vec2D<int> vec2DTetris[10];			// use this array.
	vec2DTetris[0].setDrawFunc(&Tetris::DrawLine);

	Tetris t;
	vec2DTetris[0].drawShape(t, 4);

	return 0;
}

Hope the Above Code help

Laiq Ahmed 42 Junior Poster

I've few questions,

FrameVisitor::FrameVisitor()
{
	Frame();
	frames = get_frames(myfile);
}

you have passed 'myfile' as a parameter in fstream where it is defined?

change the following Code.

list<Frame> FrameVisitor::get_frames(fstream& myfile)
	{

		char * memblock = new char [4]; //1º 4 bytes da frame...header.
		char * start = memblock;
		int i = 0;
		char c;
		list<Frame> lst;
 ...........
}

// to the below one.
list<Frame> FrameVisitor::get_frames(const char* myfilePath)
{
      fstream myfile(myfilePath, ios::in);
		char * memblock = new char [4]; //1º 4 bytes da frame...header.
		char * start = memblock;
		int i = 0;
		char c;
		list<Frame> lst;
 ...........

}

Try to pass the filePath not the streams between functions
just open the stream where required and close it after using.

as far as the problem is concerned there is no copy constructor defined for streams, whenever pass by value they'll cause problems.
check your code of class frame as well. rather than storing the stream as a member keep the file path as a member.

Hope this helps.

Laiq Ahmed 42 Junior Poster

I don't think Command Design pattern best matches your need,

what you can do is simply create a Class that holds the map of Objects of type administrator, HR, Staff and value part contains the vector of member funciton pointers. now in each object administrator, HR or Staff create some integral type upon which you'll decide which member function would be executed for selected object. or either call every registered member funciton.

//something like below.
typedef void (T::*MEMFuncPtr)(int id);
map<T, vector<MEMFuncPtr> > fMap;

check for the Chain of Responsiblity Design pattern. your requirement matches that pattern.

As far as Factory Method is concern its simple man. provide the Create function in every member class and create the abstract factor which would be templatized.

Laiq Ahmed 42 Junior Poster

it depends on the compiler rather than C++, you should see the compiler reference manual.

Laiq Ahmed 42 Junior Poster

I think you are trying to acheive the below one.

template<class T>
class Foo {
	typedef void (T::*MFPtr)(int id);
	MFPtr funcPtr;
public:
	void SetDrawFunction(MFPtr memFunctionPtr) { 
		this->funcPtr = memFunctionPtr;
	}

	void Draw(T obj, const int Id) {
		return (obj.*funcPtr)(Id);
	}
};


class Bar { 
	
public:
	void DoIt(int id) {
		cout <<"Ahaan I am Called from Foo"<<endl;
		cout << "Value of my Id is : "<<id <<endl;
	}
};


int main ()
{

	Foo<Bar> f;
	f.SetDrawFunction(&Bar::DoIt);
	
	Bar b;
	f.Draw(b, 4);

	return 0;
}

basically you are declarnig pointer to function and storing pointer to member function.

Laiq Ahmed 42 Junior Poster

sorry PETER_APIIT but your design has several flaws, describe you requirement a bit, then I will tweak your design to meet your needs.

Laiq Ahmed 42 Junior Poster

Read the following Link Carefully and check for MACRO & GUID that needs to be defined in case of XP, I am assuming that you are good in understanding msdn doc. If you still find it difficult to implement I will provide you the sample.

http://msdn.microsoft.com/en-us/library/bb773352(VS.85).aspx

Hope the above link helps.

Laiq Ahmed 42 Junior Poster

Hi,
why you've called LoadBitmap(...) in WM_CREATE message? I am sure your problem will be resolved if you change WM_CREATE to WM_INITDIALOG.
further you should learn and understand the difference between WM_CREATE & WM_INITDIALOG.

Laiq Ahmed 42 Junior Poster

peek basically reads the next available character without moving the file pointer.

for example if text file contains the following text

Hello, World

and if you execute the following psuedo Code

int main ()
{
   // open stream.
   char v =  f.peek();

 // the below line will print 'H' but will not extract this character from stream.
  cout << v <<endl;
}

if you don't want to move your reading cursor and wants to check which character will be read next you should use peek.

Laiq Ahmed 42 Junior Poster

yes Its seems fine with a cursory look.

Good luck (Y).

Laiq Ahmed 42 Junior Poster

try the below one

//HANDLE hPort = CreateFile("COM1", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
HANDLE hPort = CreateFile(TEXT("COM1"), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

Hope the above help, you didn't ask what is LPCWSTR ok :). So I am providing the solution only :P.

Laiq Ahmed 42 Junior Poster

@firstPerson the default Constructor & Destructor are not always trivial at the Compiler level, to users it might be...

Hi lotrsimp12345,

This usually irritates the programmer that why the compiler emits a default constructor.

Let me explain you a bit detail of how C++ standard dictate about default constructor and its semantics.

if your class contains primitive types, then your default constructor would be trivial i.e.

class Foo {
public:
  int a;
}

if we consider the Foo class its default constructor would be trivial i.e. doesn't modify the state and probably member "a" contains the garbage (or some 0xCCCCCCCC etc). Basically in C++ its always the programmer's responsiblity to intialize the values. This is what standard tells us. Logically if we look with the eye of programmer it seems irritating for us to explicitly intialize the value, yes it is, but we have some other facilities (default argument values) in the language to acheive the same.

class Foo { 
    Bar b;
}

In above code Bar is the subobject which must be initialized before the intialization of Foo in this case compiler synthesized the constructor which in turns calls the default constructor for Bar. same goes for inheritance as well and obviously destructor would release the memory by calling the destructor of subobjects.

if C++ default constructor initializes the memory to "ZERO values" for primitive types then the name of default constructor should be "ZERO Constructor" :) rather than default constructor.

DangerDev commented: very informative. +3
Laiq Ahmed 42 Junior Poster

Serialization & Deserialization technique would help you in acheiving this. or rather use the Boost which will provide you serialization & deserialization by not doing lot of work.

check the below link
http://www.codeproject.com/KB/cpp/InterprocessSingleton.aspx

Laiq Ahmed 42 Junior Poster

I think you are mixing the pointer to Function with Pointer to member Function, I am giving you a little example on How to solve your problem.

class Foo {
public:
	bool operator()(const int a) {
		return (a==1);
	}
};


// Don't pass Pointer to Function.
typedef bool (*PF)(const int);
//bool DoSomething(PF pFunction) {
bool DoSomeThing(Foo& f) {	
	return f(1);
}

typedef bool (Foo::*PMF)(const int a);
bool DoSomeThingElse(Foo& obj, PMF pMemFunction) {
	return (obj.*pMemFunction)(1);
}

int main()
{
	Foo f;
	bool ans = DoSomeThing(f);
	PMF pMemFunc;
	
	bool memFunction = DoSomeThingElse(f, &Foo::operator ());

	return 0;
}

In the Code above I commented the pointer to function because in your case you are using Functor or Function object which are treated as pointer to member function, so I beleive passing the object directly or passing the object and pointer to member function are the solutions to your problem. I think code explains the difference between the two.

Hope this helps!.

Laiq Ahmed 42 Junior Poster

i) create an event and check that event in the child thread

ii) signal the event from main thread when you want to exit

iii) call UnhookWindowEx() and release resouces in the child thread.

psudo code

LONG WINAPI ThreadFunc(LPVOID arg)
{

  HANDLE hEvent = OpenEvent(...,"ChildEvent");
  
  // Perform Coding.

  // here you can check whether the event is signalled or not.
   WaitForSingleObject(hEvent, INFINITE); 

}

int main ()
{
 // .. Something like below
  HANLDE hEvent = CreateEvent(...);
  HANDLE hThread = _beginthreadex(...., ThreadFunc);

 // perform the coding of main thread.

  // Signal the Event, if the child thread is still running.
  GetExitCodeThread(hThread, &dwExitCode);
  if (dwExitCode == STILL_ACTIVE)
      SetEvent(hEvent);

  // still for the safe side
  WaitForSingleObject(hThread, INFINITE);   

  CloseHandle(hThread);
  CloseHandle(hEvent);

}

Well in the ThreadFunc I've called the WaitForSingleObject(..., INFINITE) you must know how to change it to wait for the specified Time, if you are not willing to wait synchronously (INFINITE LY).

Another Way is use the SendMessage Or PostMessage API.

Laiq Ahmed 42 Junior Poster

if you are using pthread then you can use the following API.

int pthread_attr_setschedparam(pthread_attr_t *tattr, const struct sched_param *param);

consult google for such questions :). it will show you more answers.

Laiq Ahmed 42 Junior Poster
Laiq Ahmed 42 Junior Poster

I am sure that your BSTreeNode calss must be template class and you should provide the template argument to this as well.
like

BSTreeNode<DataType, KeyType>* BSTree<DataType, KeyType>::findMin (BSTreeNode<DataType, KeyType>* root) const {
// Implimentation ... 
}

.
otherwise provide the implementation of class BSTreeNode to identify the exact error.

Hope this helps

Laiq Ahmed 42 Junior Poster

First of all for all native Applications written in C/C++ no Framework is required, well as you are using MFC in your project I think you must know the basics of Dll & CRT. In VS2008 create a Win32 Console Application and write a simple hello world program deploy that program on the machine and you'll be sure that no Framework requirement is there, check the CRT you are linking with make it statically linked, in your case I think you are dynamically linking with CRT /MDd compiler switch MSVCRTD.dll which is the default option in VS2008. try using the /MTd or /MT which will link statically with your binary.

Install the microsoft Redistributable Package for your version (VS2008 in your case) on the machine, on which you are going to deploy the .exe. If you are using MFC then you either statically link with MFC or if you dynamically link with it then you must ship mfc with that.

Learn static and dynamic learning for more informaiton.


In any case you don't need to install the framework on the target machine if you are using the Native languages C/C++.

Hope this helps

Laiq Ahmed 42 Junior Poster

hi folks,

I have some 247 warnigs are same type warning

C4996: 'fopen' was declared deprecated

I am using makefile to compile my cpp program in Visual studio 2005.

I have added _CRT_SECURE_NO_DEPRECATE in preprocessor definition too. but still I do get the warnings . Could anyone help me?

I assume that you understand why Microsoft Compiler gives this warning... so explaining the solution...

if you use precompiled headers add the following lines in the stdafx.h and rebuild the project.

#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_NONSTDC_NO_DEPRECATE

another would be include the warning in the ignore specific warning in the project settings or defining the following pragma before using any deprecated function.

#pragma warning (disable : 4996)

or add the compiler directive /D _CRT_SECURE_NO_DEPRECATE /D _CRT_NONSTDC_NO_DEPRECATE.

Well I used the IDE to compile, and I use the _CRT_SECURE_NO_DEPRECATE in the preprocessor and it has worked for me, didn't try with make files, but I am sure with the first solution that it would work if you are using the precompiled headers, disabling the 4996 warning altogether is not a good practice I think, although it is another solution to your question.

Hope the above help. Get back to us if you still get warning.

Laiq Ahmed 42 Junior Poster

tom Gun


I have a function under Base class and at the definition tine of this base class function I need to call another function which is define under the Derived class. how to do this??

As per the OOP paradigm strickly speaking in OOP, whenever you need the default behavior in Generic Type & want to specialize the behavior in derived you use the polymorphic behavior. Or if you just wanted to delegate the implementation on derive classes you can do so the concept of pure virtual function in that scenario generic type cannot define the implementation perfect example is shape heirarchy in that Draw () = 0 must be pure virtual and derived classes triangle, square etc should implement that.

well I look this query as a try to acheive

Multiple dispatch ideom

.


Well I can write article on that, but try to reuse the existing one over the internet :) hope this helps

Laiq Ahmed 42 Junior Poster

Read about OWNER DRAW Window's Style and Windows Subclassing and also Non Client Paint Message.

Following Link would help but pre-requisit are the above two concepts.

http://www.codeguru.com/cpp/controls/controls/tabcontrols/article.php/c2237

the Below is the link of VB Code just check How API's are being called.
http://www.vbaccelerator.com/home/VB/code/Controls/Tab_Controls/MDI_Tabs/article.asp


try this tutorial, if no luck then get back here again :). I will debug with you again..

Laiq Ahmed 42 Junior Poster

basically whenever process is shutdown windows releases all the memory allocated by it, the problem regarding memory leak appears whenever the application kept on running and own the unreferenced memory.

further you can simulate the scenario by creating an independent application and causing a crash, division by zero etc. and check, you can run multiple instances of this application to figure out the behavior.

basically what you are trying to acheive is the static flavour for connection and you know the life time of static variable. Just close the connection and release all the resources if you just wanted to query once or you know the point after which no more DB interaction is required, it all depends on the logic.


If the multiple instances of the same process are open, then each would have the different copy of handles so don't need to worry about them.

[Hope This Helps :)]

Laiq Ahmed 42 Junior Poster

Why don't you keep the connection level stuff at the application/module level rather than within the function, so when the game started the delay is bearable.

follow anciant dragon's advice and try using the concept of database pooling as well, these together will increase your frame-rate back to the one you've configured.

Laiq Ahmed 42 Junior Poster

search for the WinINet. for Http.

Laiq Ahmed 42 Junior Poster

I don't understand your objective behing calling derive funciton in base at all, I understand C++ is multi paradigm language, but I can't see any logical reasoning behind this, could you please elloborate more.. so we can provide you better alternative than this, or correct any mistakes whatsoever

siddhant3s commented: So true, So true +16
Laiq Ahmed 42 Junior Poster

try adding the following code in the very beginning.

#include <string>
using std::string;

this is the solution I can suggest without looking at the .zip file :)
Hope this helps.
Good luck.

Laiq Ahmed 42 Junior Poster

I can see problem here.

for(int i=0; i<int_totalNumChildren; i++) {
          genTree->int_transactionID = tranID[i];

// in main
int tID = 100; 
gTree->addChildren(&tID, numOfChildren);


}

The problem is clear you have passed the address of local variable tID and you are treating it as an array.

what you actually trying to acheive by this?. describe the logic then we'll provide you the most appropriate solution for your case.

Laiq Ahmed 42 Junior Poster

by the way following is also a legal syntax.

(obj.*m['a'])();

:).

Laiq Ahmed 42 Junior Poster

try the following.

the syntax seems difficult but look it carefully.

(f.*((*it).second))();
(f.*(it->second))();

the easier way is to create the typedef and assign the return value of m to that, and then call that pointer to member function.

like below.

typedef void (A::*FMemPtr)(void);

map<char, FMemPtr> m;
m['a'] = &A::func;

FMemPtr funcPtr = m['a'];
A obj;
(obj.*funcPtr)();

same goes for iterator.

hope this helps

Laiq Ahmed 42 Junior Poster

start quote:

#include<iostream>
#include<vector>
#include<sstream>
#include<algorithm>
#include<cmath>
#include<string>
using namespace std;

class ComboLength
{
    public:
    int howLong(string moves)
    {
        vector<int> cc;
        int i,j,k=0;
        for(i=0;i<moves.size()-1;++i)
        {
            if(moves[i]==moves[i+1])       //Error
            k++;
            else
            cc.push_back(k);
        }
        return *max_element(cc.begin(),cc.end());
    }
};

I get a segementaion error in line if (moves[i]==moves[i+1])
any idea why?

i can see the problem here..

return *max_element(cc.begin(),cc.end());

it shouldn't be like that, what if no values are being inserted in the vector. and your test [icode] moves[i] == moves[i+1] succeeded all the time then vector "cc" will be empty and max_elements return the last iterator which is not an element. and dereferencing an unknown element is segmentation fault.. (in complete description but sufficient at this level).

so change this code to following.

vector<int>::iterator maxIter = max_element(cc.begin(),cc.end());
if (maxIter != cc.end()){ 
     return *maxIter;               // not a good way either. but will work.
} 
else {
     return -1;                       // logically indicatting no value depends on implementation.
}

Hope this helps

Laiq Ahmed 42 Junior Poster

Hi All:

I have a large number of elements to be stored into vector or basic string(delimited by \n). I need to search for an element and I would like to know what is faster:

A:

std::string str = "\nElement1\nElement2...element1000\n"
str.find("\nElement3\n");

B:

std::vector<string> v;
v.pushback("Element1"); v.pushback("Element2");  ....
std::find(v.begin(), v.end(), "Element3") != v.end() )

I'm only interested in search time, I don't need to access any of the elements for reading, modifying or removing.

Thanks a lot,
Petry

try to figure out the algorithm used behind string.find(...), and compare it with standard string searching algorithm likes.

Rabin-Carp
Boyer- more
etc

the above algorithms have different complexity based on the size of the substring and size of the string in which you wanted to search teh substring... (its totally your effort.., see the STL string code and figure out).

as far as vector is concern again the complexity does matter.
if the size of the string is N elements(ignoring the string comparision cost). its O(N)...

its upto the implementation in which you are about to use .., because vector is more managed then the string which is delimited by some character(in your case \n).

what if you write the modified algorithm that meets your need, like binary search for vector container. or use some other container like BST or hash tables...

or use the STL binary_search with the predicate on string comparision.
Hope this helps

Laiq Ahmed 42 Junior Poster

Why you search for the Random Value? is it your requirement? int a=1 + int (10 * rand() / ( RAND_MAX + 1 ) ); this would result in a random number, theoratically every time you are creating a new integer to search (i.e. for each loop iteration theoretically a would be different.

why are these assignments? num=n; this would override the value of num passed?
hmmm, few problems? tell me what actually you want to achieve with this link list? we'll provide you the solution

Laiq Ahmed 42 Junior Poster

The Below Code might Help just remember MessageBox Returns the Value just store that Value and then Process that response rather than calling the message box again and again.

int nResponse = MessageBox(NULL, TEXT("Hello, World"), TEXT("Say Yes No Cancel"), MB_YESNOCANCEL);

	if (nResponse == IDYES) {
		MessageBox(NULL, TEXT("Hey You Pressed Yes!"), TEXT("Wow! Got It"), MB_OK |MB_ICONEXCLAMATION);
	}
	/*else if(...) {
	}
	else if (...) {
	}*/

One more thing why if (....) and if (....) two times, if you notice your code, you'll find one more thing
you check the first condition then again you check for some other condition.
why is that so, logically and as per the requirement, you just need to show the form & store it response & then process that response rather than calling the MessageBox API again and again.


Hope this might help

Laiq Ahmed 42 Junior Poster

I think you better try WTL/ATL, you might find it interesting.

Laiq Ahmed 42 Junior Poster

Read the Following Article

http://msdn.microsoft.com/en-us/library/64hyx33x.aspx

if it doesn't help you I will provide you the sample Code as well as steps

Laiq Ahmed 42 Junior Poster
Laiq Ahmed 42 Junior Poster

I replaced it to: while( Ptr != 0) But I still have the same problem.
I think I have to replace if(Ptr->Info.Age == Ptr->Next) but I don't find the right way.

Here is a sample code, thanks for your efforts :).

template<class T>
class Node { 
	T _element;
	Node* _next;
public: 
	Node(const T& element, Node* next = 0) : _element(element), _next(next) {}

	T Element() const { return _element; }

	Node*& Next() {	return _next; }

};


template<class T>
class LinkList { 
	Node<T>* _head;

public:
	LinkList() : _head(0) {}
	bool Insert(const T& element);
	void PrintList() const;
};

template<class T>
bool LinkList<T>::Insert(const T& element) 
{
	
	if (!_head) {
		_head = new Node<T>(element);
		return true;
	}

	if (element == _head->Element ()) {
		return false;
	}

	// Temporary pointer to head.
	Node<T>* _headIter = _head;
	bool bRepeated = false;
	while (_headIter->Next()) {
		if (element == _headIter->Element()) {
			bRepeated = true;
		}
		_headIter = _headIter->Next();
	}
	
	if (bRepeated) {
		cout<<" Repeated: element is : "<< element <<endl;
	}
	else {
		_headIter->Next() = new Node<T>(element);
	}

	return true;
}

template<class T> 
void LinkList<T>::PrintList() const
{
	Node<T>* _headIter = _head;
	while (_headIter) {
		cout<<"The element is : " << _headIter->Element()<<endl;
		_headIter = _headIter->Next();
	}
}

try to acheive this task its interesting one
there is a link list with repeated elements remove all the repeated elements :).

Laiq Ahmed 42 Junior Poster

Oh ok I see. I don't know why but when I add an element (using this code) and press Enter, a windows error occur and the terminal closes. Any ideas?

Yes! there are other mistakes in your code which I didn't touch :). while( Ptr->Next != NULL) should be replaced.

other misakes are there as well.

Laiq Ahmed 42 Junior Poster

because You allocated the element on Heap in the beginning and you should release its memory if its a repeated element otherwise you'd have a memory leak.

Laiq Ahmed 42 Junior Poster

Sorry I forgot ( I remember I used them though) Anyways.
The problem is that when I make an insertion of an element, I don't want to insert a repeated element, so if I inserted (Age = 20) and then If I insert (Age = 20) my list should have only one person who Age is 20, i don't want two ages of 20 in my list. Insertion without repeating elements.

template <typename ListElement>
void List <ListElement>::Insert()
{
NodePtr Ptr;
Ptr = new Node;
bool repeated = true;

if (Ptr == NULL)
{
cout << "Error: Insuficient Storage " << endl;
exit(1);
}

cout << " Enter The Social Security Number of New Student: ";
cin >> Ptr->Info.SSN;
cout << "Enter The Age of This Student: ";
cin >> Ptr->Info.Age;

while( Ptr->Next != NULL)
{
if(Ptr->Info.Age == Ptr->Next->Info.Age)
repeated = false;
break; // This break is for not to add the element

Ptr = Ptr->Next;


}

Ptr->Next = Head;
Head = Ptr;

if(repeated = false)
cout << "repetition just ocurred" << endl; // This is just 4 me to verified if the function works



}

I've changed your code

template <typename ListElement>
void List <ListElement>::Insert()
{
NodePtr Ptr;
Ptr = new Node;
bool repeated = false;

  if (Ptr == NULL)
 {
    cout << "Error: Insuficient Storage " << endl;
    exit(1);
 }

  cout << " Enter The Social Security Number of New Student: ";
  cin >> Ptr->Info.SSN;
  cout << "Enter The Age of This Student: ";
  cin >> Ptr->Info.Age; …
Laiq Ahmed 42 Junior Poster

Thanks ArkM I've gone through this article of Bjarne, no contradiction with this document at all, but as an experienced programmer what do you think of requirements,
practically speaking
"One day your boss come to your desk and ask I've bought a library written in C and I want you to use that for blah blah?"
or what if your boss ask you to develop a C library itself ?
I am not telling you that C is superior than C++, but the thing that matter is requirements, if someone asks for C code teach them C but also provide them with the C++ implementation and the differences between the two. I think this is better learning approach.