简体   繁体   中英

conversion from 'unsigned int' to 'int' requires a narrowing conversion

My code includes the following, and I get the error message above based on the last line below.

struct List {
    int word_i;
    int mod_i;
    char mod_type;
    char mod_char;
};

struct Morph {
    Options mode;
    deque<List> search_list;
    vector<string> dictionary;
    vector<bool> discovered;
    string output;
    int sel_word_i = 0;
    bool end_found = 0;
};

// later on in a function:
morph->search_list.push_back({ morph->dictionary.size() - 1, 0, 0, 0 });

You can replace the last line with:

morph->search_list.emplace_back( morph->dictionary.size() - 1, 0, 0, 0 );

Thus the object is created not through brace initialization which does not allow narrowing conversion.

The narrowing conversion is from the return value of the call to size which returns std::size_t which is unsigned.

For why size() - 1 is not converted to a signed value see: C++ Implicit Conversion (Signed + Unsigned)

When and after you applied what Amir suggested, you may get an error saying something like, "this function does not take (3) arguments." To fix that you'll have to declare a constructor in the class, which you used for your vector, that takes that particular number of arguments. From what I understood when you replace push_back(); with emplace_back(); the compiler thinks that you're trying to pass some variables to the constructor, which are the supposed arguments.

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