for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
std::get<0>(t) < 10;
++std::get<0>(t)) {
auto& i = std::get<0>(t);
auto& s = std::get<1>(t);
auto& v = std::get<2>(t);
std::cout << s << std::endl; // cout Hello world
v.push_back(i); // add counter value to the vector
}
C++98 and C++03 您可以明确命名 std::pair 的类型 . 但是,没有标准的方法可以将其概括为两种以上类型:
{
int i;
char x;
for(i = 0, x = 'p'; ...){
...
}
}
只需在自己的范围内声明它们 .
0
请参阅“Is there a way to define variables of two types in for loop? " for another way involving nesting multiple for loops. The advantage of the other way over Georg's " struct trick”,它(1)允许您混合使用静态和非静态局部变量,(2)它允许您拥有不可复制的变量 . 缺点是它的可读性要低得多,而且效率可能会降低 .
6 回答
不可能,但你可以这样做:
或者,使用其他括号明确限制
f
和i
的范围:不 - 但从技术上讲,有一种解决方法(不是我实际上使用它,除非被迫):
C++17 : Yes! 您应该使用structured binding declaration . gcc-7和clang-4.0(clang live example)支持该语法 . 这允许我们像这样解压缩一个元组:
以上将给你:
int i
设为1
double f
设为1.0
std::string s
设为"abc"
请确保
#include <tuple>
用于此类声明 .如果要为类型命名,可以像
std::string
一样输入tuple
中的确切类型 . 例如:C++14 :您可以使用基于类型的
std::get
添加与C 11(下面)相同的内容 . 因此,在下面的示例中,您可以使用std::get<int>(t)
而不是std::get<0>(t)
.C++11 :std::make_pair允许您执行此操作,以及std::make_tuple允许您执行两个以上的对象 .
std::make_pair
将在std::pair
中返回两个参数 . 可以使用.first
和.second
访问这些元素 .对于两个以上的对象,您需要使用
std::tuple
std::make_tuple
是一个可变参数模板,它将构造任意数量参数的元组(当然有一些技术限制) . 可以使用std::get<INDEX>(tuple_object)
索引访问元素在for循环体内,您可以轻松地对对象进行别名,但仍需要使用
.first
或std::get
作为for循环条件并更新表达式C++98 and C++03 您可以明确命名
std::pair
的类型 . 但是,没有标准的方法可以将其概括为两种以上类型:您不能在初始化中声明多个类型,但可以指定多个类型E.G.
只需在自己的范围内声明它们 .
请参阅“Is there a way to define variables of two types in for loop? " for another way involving nesting multiple for loops. The advantage of the other way over Georg's " struct trick”,它(1)允许您混合使用静态和非静态局部变量,(2)它允许您拥有不可复制的变量 . 缺点是它的可读性要低得多,而且效率可能会降低 .
定义一个宏:
请记住,您的变量范围也不会以这种方式在for循环中 .