初始化字符串向量数组

新手上路,请多包涵

是否可以初始化字符串向量数组?

例如:

 static std::vector<std::string> v; //declared as a class member

我使用 static 只是为了初始化并用字符串填充它。或者如果不能像我们使用常规数组那样初始化它,我应该将它填充到构造函数中。

原文由 cpx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 491
2 个回答

有点:

 class some_class {
    static std::vector<std::string> v; // declaration
};

const char *vinit[] = {"one", "two", "three"};

std::vector<std::string> some_class::v(vinit, end(vinit)); // definition

end 这样我就不必写 vinit+3 如果以后长度发生变化,请保持最新。将其定义为:

 template<typename T, size_t N>
T * end(T (&ra)[N]) {
    return ra + N;
}

原文由 Steve Jessop 发布,翻译遵循 CC BY-SA 2.5 许可协议

现在是 2017 年,但是这个帖子在我的搜索引擎中排名第一,今天首选以下方法(初始化列表)

 std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" };

来自 https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists

原文由 Alleo 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题