0
votes

So I inputted bunch of strings into a linkedlist. I tend try to input these nodes into vector. But program just kept crashing whenever I try to push_back. Here is my code. I have two class, node and heap.

heap h;
    vector<Node> *vstring;

After trying Dennis solution, I was able to fixed the problem. However I am having an another problem. To test if the content is actually in the vector

for(int i = 0; i < size; i++)
{
     cout << "content is " << h[i] << endl;
}

I get this following error. error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'std::vector') cout << *h << endl; ^ In node class, I do have the << operator overloaded.

ostream& operator<<(ostream& out, const Node &n)
{
    cout << "in operator " << endl;
    out<<n.data;
    return out;
}
2
99% of the time dynamically allocating a vector object is a mistake. Just use vector<Node> myvecNeil Kirk

2 Answers

1
votes
vector<Node> *vstring; 

is not initialized. Try

vector<Node> *vstring = new vector<Node>();
0
votes

First of all, as stated by others, you have uninitialized pointer.

Secondly, I don't see a good reason for writing:

std::vector<Node> *vstring;

instead of:

std::vector<Node> vstring;

Vector implementation will dynamically allocate its content, so you don't have to be concerned about its size. If you want to create an array of vectors, use std::vector<std::vector<Node>> vstring and getting and [i, j] element will be just like in case of arrays - vstring[i][j].

When passing h as std::vector<Node> *, h is not a vector it's a pointer. So using h[i] you are getting i-th vector under pointer h. The error you saw told you this -

operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'std::vector') cout << *h << endl;

It means that the argument of operator << is a vector (in your case cout << "content is " <<h[i]<< endl;

If you want to get element of vector under pointer h you should do h->at(i) (or (*h)[i]).

Also it would be better to use references instead of pointers, like this:

void heap::getData(std::vector<Node> &h, int size, Node* temp);

So there would be no problem with h[i].