结构向量的 C++ 初始化

C++ initialization of vector of structs

我正在尝试在 OSX Yosemite 下创建一个关键字识别子例程,请参见下面的清单。我确实有一些奇怪的事情。

我正在使用 "playground" 制作 MWE,并且项目构建看似正常,但不想 运行: "My Mac runs OS X 10.10.5, which is lower than String sort's minimum deployment target." 我什至不理解消息,尤其是不理解我的代码对排序的影响?

然后,我将相关代码粘贴到我的应用程序中,其中项目是使用 CMake 生成的,相同的编译器和相同的 IDE,在相同的配置中显示消息 "Non-aggregate type 'vector cannot be initialized with an initializer list" 在 "vector QInstructions={..}" 结构中。

在搜索类似的错误信息时,我发现了几个类似的问题,建议解决方案使用默认构造函数、手动初始化等。我想知道是否可以进行抗标准紧凑初始化?

#include <iostream>
using namespace std;
#include <vector>

enum KeyCode {QNONE=-1,
    QKey1=100, QKey2
};

struct QKeys
{      /** The code command code*/
    std::string    Instr; ///< The command string
    unsigned int    Length; ///< The significant length
    KeyCode Code;  //
};

vector<QKeys> QInstructions={
{"QKey1",6,QKey1},
{"QKey2",5,QKey2}
};

KeyCode FindCode(string Key)
{
    unsigned index = (unsigned int)-1;
    for(unsigned int i=0; i<QInstructions.size(); i++)
        if(strncmp(Key.c_str(),QInstructions[i].Instr.c_str(),QInstructions[i].Length)==0)
        {
            index = i;
            cout << QInstructions[i].Instr << " " <<QInstructions[i].Length << " " << QInstructions[i].Code << endl;
            return QInstructions[i].Code;
            break;
        }
    return QNONE;
}

int main(int argc, const char * argv[]) {

    string Key = "QKey2";
    cout << FindCode(Key);
}

在您的代码中

vector<QKeys> QInstructions={
("QKey1",6,QKey1),
{"QKey2",5,QKey2}
};

第一行数据使用括号“()”。将它们替换为赞誉“{}”,它将起作用。

另外,我看到你写了unsigned index = (unsigned int)-1;。根据标准,这是未定义的行为。这也很糟糕,因为您使用的是 C 风格的转换(参见 here)。您应该将其替换为:

unsigned index = std::numeric_limits<unsigned int>::max();

最后,我找到了正确的解决方案 Initialize a vector of customizable structs within an header file。不幸的是,替换括号没有帮助。

关于使用 -1unsigned int 设置为其可能的最高值,我发现在这种情况下使用 std::numeric_limits<unsigned int>::max() 是一种过分标准化的做法。我个人认为,只要我们使用补码表示,赋值就会正确。例如,在 http://www.cplusplus.com/reference/string/string/npos/ 你可能会读到:

static const size_t npos = -1;

...

npos is a static member constant value with the greatest possible value for an element of type size_t.

...

This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.