【问题标题】:C++ initialization of vector of structs结构向量的 C++ 初始化
【发布时间】:2015-11-18 07:45:40
【问题描述】:

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

我正在使用“操场”来制作 MWE,项目构建看起来不错,但不想运行: “我的 Mac 运行 OS X 10.10.5,低于字符串排序的最低部署目标。” 我什至不理解消息,尤其是我的代码对排序的影响?

然后,我将相关代码粘贴到我的应用程序中,其中项目是使用 CMake 生成的,并且相同的编译器和相同的 IDE,在相同的配置中显示消息 “非聚合类型的向量不能用初始化列表初始化” 在“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);
}

【问题讨论】:

  • 确保你的建筑是为 c++ 11 而不是 c++ 98。
  • 游乐场?据我所知,Playground 是一个 Swift 功能。

标签: c++ struct initialization


【解决方案1】:

在您的代码中

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

第一行数据使用括号“()”。将它们替换为 accolades "{}" 即可。

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

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

【讨论】:

    【解决方案2】:

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

    关于使用-1unsigned int 设置为可能的最高值,我发现在这种情况下使用std::numeric_limits&lt;unsigned int&gt;::max() 有点矫枉过正,这是一种过度标准化。我个人认为,只要我们使用二进制补码表示,赋值就会是正确的。例如,在 http://www.cplusplus.com/reference/string/string/npos/ 你可以阅读:

    static const size_t npos = -1;

    ...

    npos 是一个静态成员常量值,具有最大可能 size_t 类型元素的值。

    ...

    这个常数被定义为 -1,因为 size_t 是 无符号整数类型,它是最大可能表示的 此类型的值。

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2011-11-01
      • 2021-08-21
      • 2014-07-06
      相关资源
      最近更新 更多