bobthemac
bobthemac

Reputation: 1172

No matching constructor for initialisation of 'value type'

I have got some code that gets the most frequent words and puts them into a vector. I then sort the vector into numerical order and all this works fine. I then try to resize the vector to 10 so I can get the top ten that I want to sort by word.

I think the problem lies with part of my struct but i am not to sure here is the code i am using.

struct wordFreq
{
    string word;
    int count;

    wordFreq(string str, int c): word(str),count(c) { }
}; 

words.resize(10);

Any help will be appreciated.

Upvotes: 0

Views: 919

Answers (4)

Dialecticus
Dialecticus

Reputation: 16759

vector::resize function requires items to have a constructor with no parameters (default constructor). See the section "Requirements for Container Elements" in the MSDN page. The sentence "some operations on containers might also require a public default constructor" relates to vector::resize.

Upvotes: 0

avakar
avakar

Reputation: 32635

When resizing the vector, the function resize needs to know the value for the new elements. Therefore, the call

words.resize(10);

includes a default argument of the form wordFreq(), which is invalid in your case, since the class wordFreq doesn't have a default constructor.

If no new elements are being created, use erase instead of resize.

words.erase(words.begin() + 10, words.end());

Upvotes: 3

Botz3000
Botz3000

Reputation: 39620

You need to create a default constructor, since vector uses it to make room for new elements.

wordFreq() : word(""), count(0) { }

Upvotes: 0

Naveen
Naveen

Reputation: 73473

Since you are using vector::resize vector tries to create 10 object using default ctor of wordFreq class. Since there is no default ctor available you get a compiler error. For the case you are mentioning there is no need to use the resize method, you can simply loop through 1..10 to use the top 10 elements as you have already sorted the vector.

Upvotes: 1

Related Questions