对于map,tuple等类型,C++17可以通过结构化的绑定到对应的数据结构上:
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, string> m = { {1, "hi"}, {2, "hello"}};
for(auto [index, str] : m) //将index和str直接绑定到map的内部对象上
{
cout<<"index:"<<index<<" is:"<<str<<endl;
}
return 0;
}
运行程序输出:
index:1 is:hi
index:2 is:hello
这种结构化绑定也可以将变量绑定为引用及const类型:
#include <iostream>
#include <map>
using namespace std;
int main()
{
map<int, string> m = { {1, "hi"}, {2, "hello"}};
for(auto &[index, str] : m)
{