在 C++ 中直接访问的内联数组声明

Inline array declaration with direct access in c++

我想用 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 经常这样做。 它帮助我很好地分解代码。

看起来您应该使用具有 authorageobjectwhatever 属性的自定义 class 向量,将其放入一个向量并对其进行范围循环 - 这在 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

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

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