简体   繁体   中英

Error when resizing vector of template object

I am trying to create a vector of vector of a template object. The error occurs when I try to resize the inner vector and I can't make heads or tail of the error message. I don't know where it gets the HashTable::Item::Item from. Any suggestions?

/usr/include/c++/4.4.6/bits/stl_vector.h(552): error: no instance of constructor "HashTable::Item::Item [with Key=int, Value=Varvalue]" matches the argument list resize(size_type __new_size, value_type __x = value_type())

  detected during: instantiation of "void std::vector<_Tp, _Alloc>::resize(std::vector<_Tp, _Alloc>::size_type={size_t={unsigned long}}, std::vector<_Tp, _Alloc>::value_type) [with _Tp=HashTable<int, Varvalue>::Item, _Alloc=std::allocator<HashTable<int, Varvalue>::Item>]" at line 118 of "main.cc" 

Here is the relevant code:

#define VECLEN 16
class Varvalue
{
public:
        char data[32];
};

template class HashTable { private: class Item { public: bool valid; Key key; Value value; Item *next;
Item(const Key k, const Value v, Item *b = 0, bool val = true): key(k), value(v), next(b), valid(val) {} };

vector<vector<Item> > table;
    int tableSize;
    HashTable(const int s): tableSize(s)
    {
            table.resize(tableSize);
            for(int i=0; i<table.size(); i++)
                  table[i].resize(VECLEN);       // <<-- error line 118
    }

}

int main() { HashTable<int, Varvalue> htable(nkeys); }

Item doesn't have a default constructor, so you need to provide 2 arguments to resize a vector<Item> . The latter argument shall be a "default" Item with which to fill the vector.

In C++, when you declare a class and you don't provide a constructor a default constructor (without any input parameters) is automatically generated. When you do declare a constructor with input parameters you are not awarded the default constructor. In your case, you did declare a constructor for class item which needs k and v as input parameters but you failed to give them, so either declare a constructor with no input parameters for item or supply k and v.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM