【问题标题】:Inline array declaration with direct access in c++在 C++ 中直接访问的内联数组声明
【发布时间】:2018-01-21 03:09:03
【问题描述】:

我想在 c++ 中做这样的事情:

for (int i = 0, i < 3; ++i)
{
   const auto& author = {"pierre", "paul", "jean"}[i];
   const auto& age = {12, 45, 43}[i];
   const auto& object = {o1, o2, o3}[i];
   print({"even", "without", "identifier"}[i]);
   ...
}

大家都知道怎么做这种把戏吗?我在python中做了很多。 它帮助我很好地分解代码。

【问题讨论】:

  • 这看起来像......一个坏主意?为什么每次循环迭代都要构造一个数组来每次都得到一个不同的元素?先在循环外声明authors={"friedrich johann", "wolfgang", "martin"};,然后在循环中选择const auto &amp;author=authors[i];,有什么问题?
  • 你是对的,这就是解决方案。

标签: c++ arrays inline


【解决方案1】:

看起来您应该使用带有 authorageobjectwhatever 属性的自定义类的向量,将其放入向量中并对其进行范围 for 循环 - 那将是C++ 中的惯用语:

struct foo
{
    std::string author;
    int age;
    object_t object;
    whatever_t whatever;
};

std::vector<foo> foos = { /* contents */ };

for(auto const& foo : foos)
{
    // do stuff
}

如果你真的想,你可以这样做:

const auto author = std::vector<std::string>{"pierre", "paul", "jean"}[i];
//        ^ not a reference

但我不确定这会优化到什么程度。您还可以在循环之前声明这些向量并保留引用。

【讨论】:

  • 当你有很多数组时,范围 for-loop 的问题就来了。
【解决方案2】:

创建像{"pierre", "paul", "jean"} 这样的对象会产生一个初始化列表。初始化器列表没有任何 [] 运算符 Why doesn't `std::initializer_list` provide a subscript operator?。所以你应该转换为const auto&amp; author = (std::vector&lt;std::string&gt;{"pierre", "paul", "jean"})[i];。此外,在创建临时对象并且存储对临时对象的引用时,引用符号也不应该存在。

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-29
    • 1970-01-01
    • 2017-02-20
    相关资源
    最近更新 更多