Nat*_*man 223 c++ scope for-loop declaration
是否可以在C++的for循环的初始化主体中声明两个不同类型的变量?
例如:
for(int i=0,j=0 ...
Run Code Online (Sandbox Code Playgroud)
定义了两个整数.我可以在初始化主体中定义a int和a char吗?怎么做?
Geo*_*che 268
不 - 但从技术上讲,有一种解决方法(不是我实际上使用它,除非被迫):
for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a)
{
std::cout << s.a << " " << s.b << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
MK.*_*MK. 216
不可能,但你可以这样做:
float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
//...
}
Run Code Online (Sandbox Code Playgroud)
或者,明确限制范围f和i使用其他括号:
{
float f;
int i;
for (i = 0,f = 0.0; i < 5; i++)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*ing 117
C++ 17:是的!您应该使用结构化绑定声明.gcc-7和clang-4.0(clang live示例)支持该语法.这允许我们像这样解压缩一个元组:
for (auto [i, f, s] = std::tuple{1, 1.0, std::string{"abc"}}; i < N; ++i) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
以上将给你:
int i 调成 1double f 调成 1.0std::string s 调成 "abc"确保#include <tuple>这种声明.
如果你想要的东西不是默认的,或者你需要构造一些东西,你可以tuple通过键入它们来指定其中的确切类型std::string.例如:
auto [vec, i32] = std::tuple{std::vector<int>{3, 4, 5}, std::int32_t{12}}
Run Code Online (Sandbox Code Playgroud)
C++ 14:您可以使用基于类型的C++ 11(下面)执行相同的操作std::get.所以,不是std::get<0>(t)在下面的例子中,你可以拥有std::get<int>(t).
C++ 11:std::make_pair允许您执行此操作,以及std::make_tuple两个以上的对象.
for (auto p = std::make_pair(5, std::string("Hello World")); p.first < 10; ++p.first) {
std::cout << p.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
std::make_pair将返回a中的两个参数std::pair.可以使用.first和访问元素.second.
对于两个以上的对象,您需要使用a std::tuple
for (auto t = std::make_tuple(0, std::string("Hello world"), std::vector<int>{});
std::get<0>(t) < 10;
++std::get<0>(t)) {
std::cout << std::get<1>(t) << std::endl; // cout Hello world
std::get<2>(t).push_back(std::get<0>(t)); // add counter value to the vector
}
Run Code Online (Sandbox Code Playgroud)
std::make_tuple是一个可变参数模板,它将构造任意数量参数的元组(当然还有一些技术限制).可以通过索引访问元素std::get<INDEX>(tuple_object)
在for循环体内,您可以轻松地对对象进行别名,但仍需要使用for .first或std::getfor for循环条件并更新表达式
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
}
Run Code Online (Sandbox Code Playgroud)
C++ 98和C++ 03您可以明确命名a的类型std::pair.但是,没有标准的方法可以将其概括为两种以上类型:
for (std::pair<int, std::string> p(5, "Hello World"); p.first < 10; ++p.first) {
std::cout << p.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
zmb*_*ush 14
您不能在初始化中声明多个类型,但可以指定多个类型EG
{
int i;
char x;
for(i = 0, x = 'p'; ...){
...
}
}
Run Code Online (Sandbox Code Playgroud)
只需在自己的范围内声明它们.