【问题标题】:Populating a list of strings into a vector in pre C++11在 C++11 之前将字符串列表填充到向量中
【发布时间】:2013-09-30 22:16:14
【问题描述】:

首先,如果这是一个令人眼花缭乱的简单而明显的问题,我想道歉。我知道这对有专业知识的人来说是相当容易的。 C++11 允许以列表形式初始化向量:

std::vector<std::string> v = {
    "this is a",
    "list of strings",
    "which are going",
    "to be stored",
    "in a vector"};

但这在旧版本中不可用。我一直在想最好的方法来填充字符串向量,到目前为止我唯一能想到的就是:

std::string s1("this is a");
std::string s2("list of strings");
std::string s3("which are going");
std::string s4("to be stored");
std::string s5("in a vector");

std::vector<std::string> v;
v.push_back(s1);
v.push_back(s2);
v.push_back(s3);
v.push_back(s4);
v.push_back(s5);

它有效,但写起来有点麻烦,我相信有更好的方法。

【问题讨论】:

标签: c++ stdvector stdstring c++03


【解决方案1】:

规范的方法是在合适的标头中定义begin()end() 函数并使用如下内容:

char const* array[] = {
    "this is a",
    "list of strings",
    "which are going",
    "to be stored",
    "in a vector"
};
std::vector<std::string> vec(begin(array), end(array));

函数begin()end() 定义如下:

template <typename T, int Size>
T* begin(T (&array)[Size]) {
    return array;
}
template <typename T, int Size>
T* end(T (&array)[Size]) {
    return array + Size;
}

【讨论】:

  • @NemanjaBoric:当然,我使用的是begin()end()!据我所知,我是第一个在 last millennium 中公开描述该技术的人。这些函数模板也是最早的Boost contributions之一。
  • 只是为了像我这样不知道这一点的人的利益,此功能现在似乎在 Boost.Range library 中。
  • 该方案的优势在于它与C++11完美前向兼容。甚至可以将其包装在宏中,以便 looks as if initializing 一个 C 数组(也可以使其与 C++11 兼容):SOME_WRAPPER(vector&lt;string&gt; vec) = {"this is a", "list of strings", ...., };
  • 是的,在 C++11 中也是 in the iterator library
【解决方案2】:

正如克里斯所说,您可以将所有文字存储到数组中,然后从该数组初始化向量:

#include <vector>
#include <iostream>
#include <string>

int main()
{
        const char* data[] = {"Item1", "Item2", "Item3"};
        std::vector<std::string> vec(data, data + sizeof(data)/sizeof(const char*));
}

您不需要显式转换为std::string

【讨论】:

    【解决方案3】:

    如果您“卡”在 C++11 之前的 C++ 中,那么只有几种选择,它们不一定“更好”。

    首先,您可以创建一个常量 C 字符串数组并将它们复制到向量中。您可能会节省一点打字时间,但其中会有一个复制循环。

    其次,如果你可以使用boost,你可以use boost::assign's list_of as described in this answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2014-08-28
      • 1970-01-01
      • 2019-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多