Home > OS >  no matching function call to error in vector.push_back
no matching function call to error in vector.push_back

Time:11-21

I am getting the following error while compiling my C program:

error: no matching function for call to 'std::vector<ChainingTable<int>::Record, std::allocator<ChainingTable<int>::Record> >::push_back(ChainingTable<int>::Record*)'
  324 |         vector_.push_back(new Record(key, value));

The error is coming from the line:

template <class TYPE>
bool ChainingTable<TYPE>::update(const std::string &key, const TYPE &value)
{
    if (!keyExists)
        {
            vector_.push_back(new Record(key, value));
        }
}

This is defined for the class:

class ChainingTable : public Table<TYPE>
{
    struct Record
    {
        TYPE data_;
        std::string key_;
        Record(const std::string &key, const TYPE &data)
        {
            key_ = key;
            data_ = data;
        }
    };

    std::vector<std::vector<Record>> records_;
    int capacity_; // capacity of the array

Complete code:

int sz = numRecords();
bool rc = true;
std::hash<std::string> hashFunction;
size_t hash = hashFunction(key);
size_t idx = hash % capacity_;
std::vector<Record> vector_ = records_[idx];
bool keyExists = false;
for (int i = 0; i < vector_.size(); i  )
{
    if (vector_[i].key_ == key)
    {
        vector_[i].data_ = value;
        keyExists = true;
    }
}
if (!keyExists)
{
    vector_.push_back(new Record(key, value));
}

What could be the reason for this?

CodePudding user response:

Your vector is declared to store objects of type Record, not pointers to them (Record *) but you are trying to push result of operator new which returns Record *, just use std::vector::emplace_back instead:

vector_.emplace_back(key, value);

Note: in this line

std::vector<Record> vector_ = records_[idx];

you create a copy and later modify it, seems that you need a reference.

Note2: in your search loop you do not terminate even if you find object already, you should add break into if statement, that will make it more effective.

CodePudding user response:

The problem is that your variable vector_ holds objects of type Record but when you write:

vector_.push_back(new Record(key, value));

You are trying to add a pointer to a Record object in the vector vector_ instead of adding the Record object itself.

You can solve it by writing:

vector_.emplace_back(key, value);

Alternate solution

Note that there is another possible solution which is to use:

vector_.push_back(Record(key, value));

But using emplace_back should be preferred.

  • Related