Using my node structure in the STL's priority queue

I created a structure called leafNode which contains two data fields at this point (an int and a char), and would like to store it in a priority queue but am getting build errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "stdafx.h"
#include <iostream>
#include <queue>
using namespace std;

struct leafNode {
	char character;
	int count;
}*p;
void testRead(){
	priority_queue<leafNode> myqueue;
	char letter;
	p->character='~';
	p->count=0;
	for(int i =0; i<=5; i++){
		cout << "type a single character" << endl;
		cin >> letter;
		p->character = letter;
		p->count++;
		myqueue.push(*p);
	}
	while(!myqueue.empty()){
		leafNode *q;
		*q = myqueue.top();
		cout << q->character << " " << q->count << endl;
		myqueue.pop();
	}
}


To me all of this makes perfect sense, but obviously I'm wrong. Any suggestions would be appreciated.
For some reason you are creating leafNode pointers when you don't need to. You are also writing to the pointers without allocating any memory for them which can cause all kinds of trouble.

Also you have not provided an ordering function that the priority_queue can use to establish which leafNode has priority over the other.

Here is your code with some fixes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <queue>

using namespace std;

struct leafNode
{
	char character;
	int count;

	// Need a comparison function to establish the priority
	bool operator<(const leafNode& n) const
	{
		return character < n.character; // order according to character code?
	}

}; // *p; no need for global pointer


void testRead()
{
	priority_queue<leafNode> myqueue;
	char letter;

	leafNode p; // creat your leafNode locally (and not a pointer)
	p.character = '~';
	p.count = 0;

	for(int i = 0; i <= 5; i++)
	{
		cout << "type a single character" << endl;
		cin >> letter;
		p.character = letter;
		p.count++;
		myqueue.push(p);
	}

	while(!myqueue.empty())
	{
		const leafNode& q = myqueue.top();
		cout << q.character << " " << q.count << endl;
		myqueue.pop();
	}
}

int main()
{
	testRead();
	return 0;
}
type a single character
w
type a single character
r
type a single character
s
type a single character
g
type a single character
d
type a single character
j
w 1
s 3
r 2
j 6
g 4
d 5


Thank you so much for that Galik, and thank you for answering so quickly. That definitely solved the issue I was having. I was slowly arriving at this conclusion when you answered but still didn't know how to set the priority field. Thank you again.
Topic archived. No new replies allowed.