Vector error , cannot get push_back to work

user1058359 picture user1058359 · Nov 21, 2011 · Viewed 30.6k times · Source

This is just a snippet of the uncommented code. The packing vector keeps causing an error at the push_back(), and I'm not quite sure why:

EDIT: It has been updated to say

vector<BinTreeNode<HuffmanToken<Pixel>* > > packing = new vector<BinTreeNode<HuffmanToken<Pixel> > >();

however, there is still the allocator error even with the adjusted templates.

no matching function to call std::vector , std::allocator > > :: push_back(BinTreeNode > >&

BinTree<HuffmanToken<Pixel> >* Huffman::buildTree(const vector<HuffmanToken<Pixel>>& tokens) {

BinTreeNode<HuffmanToken<Pixel> >* g1 = new BinTreeNode<HuffmanToken<Pixel> >();
BinTreeNode<HuffmanToken<Pixel> >* g2 = new BinTreeNode<HuffmanToken<Pixel> >();
BinTreeNode<HuffmanToken<Pixel> >* g3 = new BinTreeNode<HuffmanToken<Pixel> >();

vector<HuffmanToken<Pixel> > packing ;

vector<HuffmanToken<Pixel> >::const_iterator it;

it = tokens.begin();

for(int i = 0; i < tokens.size(); i++) {
  g1 -> setValue(tokens.at(i));
  packing.push_back(g1);
}

Answer

Ken Wayne VanderLinde picture Ken Wayne VanderLinde · Nov 21, 2011

Your vector is expecting HuffmanToken<Pixel> objects, but you're trying to push_back a BinTreeNode<HuffmanToken<Pixel> >* pointer. Just make sure your vector has the right template type.

Edit

Considering your update, I decided to throw up all the code as it should be:

BinTree<HuffmanToken<Pixel> >* Huffman::buildTree(const vector<HuffmanToken<Pixel>>& tokens) {

    BinTreeNode<HuffmanToken<Pixel> >* g1 = new BinTreeNode<HuffmanToken<Pixel> >();
    BinTreeNode<HuffmanToken<Pixel> >* g2 = new BinTreeNode<HuffmanToken<Pixel> >();
    BinTreeNode<HuffmanToken<Pixel> >* g3 = new BinTreeNode<HuffmanToken<Pixel> >();

    vector<BinTreeNode<HuffmanToken<Pixel> >*> packing ;

    vector<BinTreeNode<HuffmanToken<Pixel> >*>::const_iterator it;

    it = tokens.begin();

    for(int i = 0; i < tokens.size(); i++) {
        g1 -> setValue(tokens.at(i));
        packing.push_back(g1);
    }

The only difference from the original code is that vector<HuffmanToken<Pixel> > is replaced with vector<BinTreeNode<HuffmanToken<Pixel> >*> (that goes for the vector itself, as well as the iterator).