【问题标题】:Initializing a static const vector of vectors in Visual Studio 2012在 Visual Studio 2012 中初始化向量的静态 const 向量
【发布时间】:2015-01-21 21:35:57
【问题描述】:

我正在尝试在 Visual Studio 2012 中创建一个 int 的 const 向量的静态 const 向量(必须有更好的方法),但我无法找出正确的语法初始化它。我相信 2012 使用的 C++ 版本不允许使用初始化程序,但我不知道如何完成我想要的。

我在 2013 年尝试过以下方法,似乎可以编译:

.h:

static const std::vector<const std::vector<int>> PartLibrary;

.cpp:

const std::vector<const std::vector<int>> Parts::PartLibrary {
    std::vector<int> { 29434 }, // 1
    std::vector<int> { 26322 }, // 2
...
}

但是,当我在 2012 年尝试相同时,它会出错:

Error   1   error C2470: 'PartLibrary' : looks like a function definition, 
but there is no parameter list; skipping apparent body

如何正确初始化它?我可以使用更合适的数据类型吗?我只是希望我的静态类有一个整数向量的常量向量,这样我就可以快速读取但不能修改值。

【问题讨论】:

  • 你编译时是否打开了 c++11 标准选项?
  • Visual Studio 2012 不完全支持 C++11。使用更新的版本。或者使用 boost assign 进行静态初始化。
  • @πάνταῥεῖ 我不知道该怎么做,但快速谷歌搜索告诉我它默认启用,但初始化列表未添加到 2012
  • @tillaert 不幸的是我必须在 2012 年做。但是,我想知道是否可以将编译器更新为支持初始化列表的版本
  • 内心的const不是完全没用吗?您不能修改最顶层的容器,因此不能修改内部容器的任何元素。

标签: c++ visual-studio-2012 vector


【解决方案1】:

在 C++ 中,您不能有 std::vectorconst 任何东西>,例如参见 here。元素必须是可分配的。

在 C++98 中,您可以尝试以下初始化方案。它的缺点是将向量从数组复制到向量中:

const std::vector<int> vectors[2] = {
    std::vector<int> (1, 29434), // vector of one element
    std::vector<int> (1, 26322), // vector of one element
};
const std::vector<std::vector<int> > /*Parts::*/PartLibrary (vectors+0, vectors+2);
// space needed for C++98---------^

【讨论】:

    猜你喜欢
    • 2012-12-15
    • 2011-04-11
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 2011-05-18
    • 1970-01-01
    • 2012-09-21
    相关资源
    最近更新 更多