从'unsigned int'到'int'的转换需要缩小的转换

问题描述

我的代码包括以下内容,并且根据下面的最后一行,我收到了上面的错误消息。

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 });

解决方法

您可以将最后一行替换为:

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

因此,对象不是通过括号初始化创建的,括号初始化不允许缩小转换。

缩小的转换是从调用的返回值到size的结果,该值返回未签名的std::size_t

关于为什么size() - 1不转换为带符号的值,请参见:C++ Implicit Conversion (Signed + Unsigned)