473,671 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

STL question: is this O/T ?

Guys,
I'm trying to compile this code to build a huffman tree, but I'm getting a
runtime error and my degugger ends up somewhere in the STL files. What am i
doing wrong. I appreciate its not effiecient/stylistic, etc, it was just
something i wanted to try
Thanks

Mike

#include <assert.h>
#include <vector>
#include <list>
using std::list;
using std::vector;
class HuffmanNode
{
public:
HuffmanNode* pLeft;
HuffmanNode* pRight;
char Represented;
float frequency;
HuffmanNode() : pLeft(NULL), pRight(NULL), Represented(-1),
frequency(-1) {}
void AddSubTreeToVec tor(vector<stri ng>& v, string currentString);
};
int main()
{
list<HuffmanNod e> nodes;
for(int i=0;i<256;i++)
{
HuffmanNode n;
n.Represented = i;
n.frequency = (i*i *10 )% 300;
nodes.push_back (n);
}
cout << "Populated Source List: " << nodes.size();

while(nodes.siz e() >1)
{
cout << "\n\tListSi ze: " << nodes.size();
HuffmanNode newNode;
newNode.pLeft = new HuffmanNode;
newNode.pRight = new HuffmanNode;

list<HuffmanNod e>::iterator it;
list<HuffmanNod e>::iterator smallest = nodes.begin();

//Find Smallest
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pLeft = *(smallest);
newNode.frequen cy = smallest->frequency;
nodes.erase(sma llest);

//Find the next Snmallest
smallest = nodes.begin();
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pRight = *smallest;
newNode.frequen cy += smallest->frequency;
nodes.erase(sma llest);
//Add the New Node
nodes.push_back (newNode);
}

HuffmanNode hmt = *(nodes.begin() );
//Move Tree into vector for encoding:
vector<string> HuffmanCodes;
for(int i=0;i<256;i++)
{
string str;
HuffmanCodes.pu sh_back(str);
}

hmt.AddSubTreeT oVector(Huffman Codes,"");
for(int i=0;i<256;i++)
{
string str = HuffmanCodes[i];
cout << i << ": " << str.c_str() << endl;
}
system("PAUSE") ;
}



void HuffmanNode::Ad dSubTreeToVecto r(vector<string >& v, string
currentString)
{
assert(this);
if(Represented != -1) v[Represented] = currentString;
//LeftSubTree
if(pLeft)
{
string LeftString;
LeftString = currentString;
LeftString.appe nd("0");
pLeft->AddSubTreeToVe ctor(v,LeftStri ng);
}
//RightSubTree
if(pRight)
{
string RightString;
RightString = currentString;
RightString.app end("0");
pRight->AddSubTreeToVe ctor(v,RightStr ing);
}
}
Jul 22 '05 #1
12 1407
Michael wrote:
Guys,
I'm trying to compile this code to build a huffman tree, but I'm getting a
runtime error and my degugger ends up somewhere in the STL files. What am i
doing wrong. I appreciate its not effiecient/stylistic, etc, it was just
something i wanted to try
Thanks

Mike
The code didn't compile in the first place.



#include <assert.h>
#include <vector>
#include <list>
using std::list;
using std::vector;
#include <string>
#include <iostream>
#include <iterator>
#include <cstdlib>

using std::string;
using std::cout;
using std::endl;

class HuffmanNode
{
public:
HuffmanNode* pLeft;
HuffmanNode* pRight;
char Represented;
float frequency;
HuffmanNode() : pLeft(NULL), pRight(NULL), Represented(-1),
frequency(-1) {}
void AddSubTreeToVec tor(vector<stri ng>& v, string currentString);
};
int main()
{
list<HuffmanNod e> nodes;
for(int i=0;i<256;i++) // Go for unsigned int or better, size_t type for indexing into
//the vector.
{
HuffmanNode n;
n.Represented = i;
n.frequency = (i*i *10 )% 300;
nodes.push_back (n);
}
cout << "Populated Source List: " << nodes.size();

while(nodes.siz e() >1)
{
cout << "\n\tListSi ze: " << nodes.size();
HuffmanNode newNode;
newNode.pLeft = new HuffmanNode;
newNode.pRight = new HuffmanNode;

list<HuffmanNod e>::iterator it;
list<HuffmanNod e>::iterator smallest = nodes.begin();

//Find Smallest
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pLeft = *(smallest);
newNode.frequen cy = smallest->frequency;
nodes.erase(sma llest);

//Find the next Snmallest
smallest = nodes.begin();
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pRight = *smallest;
newNode.frequen cy += smallest->frequency;
nodes.erase(sma llest);
//Add the New Node
nodes.push_back (newNode);
}

HuffmanNode hmt = *(nodes.begin() );
//Move Tree into vector for encoding:
vector<string> HuffmanCodes;
for(int i=0;i<256;i++)
{
string str;
HuffmanCodes.pu sh_back(str);
}

hmt.AddSubTreeT oVector(Huffman Codes,"");
for(int i=0;i<256;i++)
{
string str = HuffmanCodes[i];
cout << i << ": " << str.c_str() << endl;
}
system("PAUSE") ; // As far as possible try not to use system command. It is a separate
topic, but many programmers loathe it since it affects readability of
the code.

// Where is the return statement for main function .
}



void HuffmanNode::Ad dSubTreeToVecto r(vector<string >& v, string
currentString)
{
assert(this);
if(Represented != -1) v[Represented] = currentString;


The type of Represented happens to be a 'char' !! Change that to
size_t type. Do not make such dangerous conversions. Then heed your
compiler's warnings after converting the same to unsigned int. That
should help.
--
Karthik
Humans please 'removeme_' for my real email.
Jul 22 '05 #2
Karthik wrote:


The type of Represented happens to be a 'char' !! Change that to
size_t type. Do not make such dangerous conversions. Then heed your
compiler's warnings after converting the same to unsigned int.


Oops !! I meant size_t here , and not unsigned int.
--
Karthik
Humans please 'removeme_' for my real email.
Jul 22 '05 #3
Karthik <re************ *******@yahoo.c om> wrote in
news:4092b08f$1 @darkstar:
Michael wrote:
system("PAUSE") ;

// As far as possible try not to use system command. It is a
separate
topic, but many programmers loathe it since it affects readability of
the code.

// Where is the return statement for main function .


Not required. If main ends without a return statement, it effectively has
an automatic "return 0;". Stylistically speaking I prefer to always have
it in there anyway.....
Jul 22 '05 #4
Andre Kostur wrote:


Not required. If main ends without a return statement, it effectively has
an automatic "return 0;". Stylistically speaking I prefer to always have
it in there anyway.....


Might have been the case with a primitive compiler. Modern compilers
refuse to compile, without that ( and it does make sense to be that
way). More than return 0, I would prefer still - EXIT_SUCCESS to make it
complete.

--
Karthik
Humans please 'removeme_' for my real email.
Jul 22 '05 #5
Karthik wrote:
Andre Kostur wrote:


Not required. If main ends without a return statement, it effectively
has an automatic "return 0;". Stylistically speaking I prefer to
always have it in there anyway.....

Might have been the case with a primitive compiler. Modern compilers
refuse to compile, without that ( and it does make sense to be that
way). More than return 0, I would prefer still - EXIT_SUCCESS to make it
complete.


The return statement in main() is optional (3.6.1). If it's just going
to return a zero-valued constant, I prefer not to clutter the code with it.
Jul 22 '05 #6
Karthik <re************ *******@yahoo.c om> wrote in
news:4092c7de$1 @darkstar:
Andre Kostur wrote:


Not required. If main ends without a return statement, it
effectively has an automatic "return 0;". Stylistically speaking I
prefer to always have it in there anyway.....


Might have been the case with a primitive compiler. Modern
compilers
refuse to compile, without that ( and it does make sense to be that
way). More than return 0, I would prefer still - EXIT_SUCCESS to make
it complete.


Then the modern compilers would be refusing to compile a well-formed C++
program. (Section 3.6.1.5).
Jul 22 '05 #7
Karthik wrote:
Andre Kostur wrote:


Not required. If main ends without a return statement, it
effectively has
an automatic "return 0;". Stylistically speaking I prefer to always
have it in there anyway.....
Might have been the case with a primitive compiler.


If by 'primitive' you mean standard compliant.
Modern compilers refuse to compile, without that ( and it does make
sense to be that way).
It may make sense, but you should still replace those "modern compilers"
by old-fashioned
More than return 0, I would prefer still - EXIT_SUCCESS to make
it complete.


--
Prof: I'm sorry, Fry, but astronomers renamed Uranus in 2620
to end that stupid joke once and for all.
Fry: Oh. What's it called now?
Prof: Urectum.
(ü+#äfrom Futurama)
fro,.-m Futurama)

Jul 22 '05 #8
Guys, thanks for advice on style but you haven't replied to my actual
question, whats wrong with the code, why does it crash??


"Rolf Magnus" <ra******@t-online.de> wrote in message
news:c6******** *****@news.t-online.com...
Karthik wrote:
Andre Kostur wrote:


Not required. If main ends without a return statement, it
effectively has
an automatic "return 0;". Stylistically speaking I prefer to always
have it in there anyway.....


Might have been the case with a primitive compiler.


If by 'primitive' you mean standard compliant.
Modern compilers refuse to compile, without that ( and it does make
sense to be that way).


It may make sense, but you should still replace those "modern compilers"
by old-fashioned
More than return 0, I would prefer still - EXIT_SUCCESS to make
it complete.


--
Prof: I'm sorry, Fry, but astronomers renamed Uranus in 2620
to end that stupid joke once and for all.
Fry: Oh. What's it called now?
Prof: Urectum.
(ü+#äfrom Futurama)
fro,.-m Futurama)

Jul 22 '05 #9
Michael,

Karthik had the right hint. Represented not only happens to be a char
(and you are using it as an index to a vector -- which should be a size_t),
but worse, you allow it to assume values out of range to your vector. The
problem is here:

if(Represented != -1) v[Represented] = currentString;

I don't understand the conversion very well, but it will run if you only
change the above line to:

if(Represented < -1) v[Represented] = currentString;

or:

if(Represented > -1) v[Represented] = currentString;
(and I guess this gives the result you want)

or even:

if((Represented != -1) && (size_t(Represe nted) < v.size())) v[Represented] =
currentString;

or you can just keep it as it is and change the type of Represented to int.

This solves this problem, but I think other may appear further on.
Especially because you are using new to allocate memory, but you are not
deleting the new objects anywhere. Another problem is that you are not
defining a copy constructor and an assignment operator. This produce
surprising restults in many cases. The problem is that you have pointer
members and if you don't tell the compiler how to copy them, the compiler
will copy only their *addressess*.
So, I recomend that you define a destructor, a copy constructor and an
assignment operator for HuffmanNode.

Below is a code that compiles an runs withou errors (I just included some
extra headers and changed the type of Represented to int)

// -------------- start --------------------

#include <iostream>
#include <assert.h>
#include <vector>
#include <list>
#include <string>
using namespace std;
class HuffmanNode
{
public:
HuffmanNode* pLeft;
HuffmanNode* pRight;
int Represented;
float frequency;
HuffmanNode() : pLeft(NULL), pRight(NULL), Represented(-1),
frequency(-1) {}
void AddSubTreeToVec tor(vector<stri ng>& v, string currentString);
};
int main()
{
list<HuffmanNod e> nodes;
for(int i=0;i<256;i++)
{
HuffmanNode n;
n.Represented = i;
n.frequency = (i*i *10 )% 300;
nodes.push_back (n);
}
cout << "Populated Source List: " << nodes.size();

while(nodes.siz e() >1)
{
cout << "\n\tListSi ze: " << nodes.size();
HuffmanNode newNode;
newNode.pLeft = new HuffmanNode;
newNode.pRight = new HuffmanNode;

list<HuffmanNod e>::iterator it;
list<HuffmanNod e>::iterator smallest = nodes.begin();

//Find Smallest
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pLeft = *(smallest);
newNode.frequen cy = smallest->frequency;
nodes.erase(sma llest);

//Find the next Snmallest
smallest = nodes.begin();
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pRight = *smallest;
newNode.frequen cy += smallest->frequency;
nodes.erase(sma llest);
//Add the New Node
nodes.push_back (newNode);
}

HuffmanNode hmt = *(nodes.begin() );
//Move Tree into vector for encoding:
vector<string> HuffmanCodes;
for(int i=0;i<256;i++)
{
string str;
HuffmanCodes.pu sh_back(str);
}

hmt.AddSubTreeT oVector(Huffman Codes,"");
for(int i=0;i<256;i++)
{
string str = HuffmanCodes[i];
cout << i << ": " << str.c_str() << endl;
}
system("PAUSE") ;
}



void HuffmanNode::Ad dSubTreeToVecto r(vector<string >& v, string
currentString)
{
if(!this) return;
if(Represented != -1) v[Represented] = currentString;
//LeftSubTree
if(pLeft)
{
string LeftString;
LeftString = currentString;
LeftString.appe nd("0");
pLeft->AddSubTreeToVe ctor(v,LeftStri ng);
}
//RightSubTree
if(pRight)
{
string RightString;
RightString = currentString;
RightString.app end("0");
pRight->AddSubTreeToVe ctor(v,RightStr ing);
}
}

// -------------- end --------------------

"Michael" <sl***********@ hotmail.com> wrote in message
news:c6******** **@sparta.btint ernet.com...
Guys,
I'm trying to compile this code to build a huffman tree, but I'm getting a
runtime error and my degugger ends up somewhere in the STL files. What am i doing wrong. I appreciate its not effiecient/stylistic, etc, it was just
something i wanted to try
Thanks

Mike

#include <assert.h>
#include <vector>
#include <list>
using std::list;
using std::vector;
class HuffmanNode
{
public:
HuffmanNode* pLeft;
HuffmanNode* pRight;
char Represented;
float frequency;
HuffmanNode() : pLeft(NULL), pRight(NULL), Represented(-1),
frequency(-1) {}
void AddSubTreeToVec tor(vector<stri ng>& v, string currentString);
};
int main()
{
list<HuffmanNod e> nodes;
for(int i=0;i<256;i++)
{
HuffmanNode n;
n.Represented = i;
n.frequency = (i*i *10 )% 300;
nodes.push_back (n);
}
cout << "Populated Source List: " << nodes.size();

while(nodes.siz e() >1)
{
cout << "\n\tListSi ze: " << nodes.size();
HuffmanNode newNode;
newNode.pLeft = new HuffmanNode;
newNode.pRight = new HuffmanNode;

list<HuffmanNod e>::iterator it;
list<HuffmanNod e>::iterator smallest = nodes.begin();

//Find Smallest
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pLeft = *(smallest);
newNode.frequen cy = smallest->frequency;
nodes.erase(sma llest);

//Find the next Snmallest
smallest = nodes.begin();
for(it = nodes.begin();i t != nodes.end();it+ +)
if(it->frequency <= smallest->frequency) smallest = it;
*newNode.pRight = *smallest;
newNode.frequen cy += smallest->frequency;
nodes.erase(sma llest);
//Add the New Node
nodes.push_back (newNode);
}

HuffmanNode hmt = *(nodes.begin() );
//Move Tree into vector for encoding:
vector<string> HuffmanCodes;
for(int i=0;i<256;i++)
{
string str;
HuffmanCodes.pu sh_back(str);
}

hmt.AddSubTreeT oVector(Huffman Codes,"");
for(int i=0;i<256;i++)
{
string str = HuffmanCodes[i];
cout << i << ": " << str.c_str() << endl;
}
system("PAUSE") ;
}



void HuffmanNode::Ad dSubTreeToVecto r(vector<string >& v, string
currentString)
{
assert(this);
if(Represented != -1) v[Represented] = currentString;
//LeftSubTree
if(pLeft)
{
string LeftString;
LeftString = currentString;
LeftString.appe nd("0");
pLeft->AddSubTreeToVe ctor(v,LeftStri ng);
}
//RightSubTree
if(pRight)
{
string RightString;
RightString = currentString;
RightString.app end("0");
pRight->AddSubTreeToVe ctor(v,RightStr ing);
}
}


Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3096
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
4
2870
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
5031
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
11
1739
by: billnospam | last post by:
Is it possible to overload operators in vb.net? Is it possible to do programmer defined boxing on byvalue variables in vb.net?
2
1972
by: amelia170 | last post by:
I am creating a database with a yes or no answer for question 1. Based on that answer, (if they answer yes) they will answer question 2, then three....However, if they answer no to question one, I want them not to be able to answer question 2 at all. Ideas? Thanks so much!
3
3078
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table before rowID answID qryrow questionID datafield 1591 12 06e 06e 06e question 1593 12 06f 06f 06f question 1594 12 answer to the question 06f
1
3613
by: chiefs | last post by:
I'm tyring to get the output of the Question # with last question at the end. Here is the code: Instead of printing the # after the Question, it prints the ASCII Characters. /* print question# (loop) */ #include <stdio.h> #include <string.h> main()
15
2147
by: Gary Peek | last post by:
Can anyone tell us the browsers/versions that exhibit errors when tables are nested too deeply? And how many levels of nesting produces errors? (not a tables vs CSS question)
37
2139
by: Prafulla T | last post by:
Assume that an integer pointer x is declared in a "C" program as int *x; Further assume that the location of the pointer is 1000 and it points to an address 2000 where value 500 is stored in 4 bytes. What is the output of printf("%d",*x); a) 500 b) 1000 c) undefined d) 2000 What will be the answer? I think it should be ( c) bcoz on m/c will little endian sys it will print 500 & those with big endian it will print 0
0
1300
by: knorth | last post by:
If you submit the best question for the workshop at LinkedData Planet, you'll win admission to the conference, including keynotes by W3C Director Sir Tim Berners-Lee and IBM CTO for Information Management Anant Jhingran. -------------------------------------------------- Are you applying semantic technologies for web or enterprise applications? Do you have a problem or question related to RDF, SPARQL, taxonomies, ontologies or semantic...
0
8403
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8930
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8605
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7446
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6238
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5704
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4417
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2062
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.