c++17 structure binding
今天在leetcode上看到了一个以前没见过的c++遍历容器的方法:
unordered_map<int,int> map;
for(auto& [_,v] : map)
{
cout<<v<<endl;
}
然后找了下才明白,这是c++ 17引入的一个新的语法糖,叫structure binding。
很好很强大,终于能和python一样方便的比哪里了,类似 for k,v in m.items(),舒服
下面是我简单试试range based for 和structure binding的小程序
#include <iostream>
#include <unordered_map>
using namespace std;
class A_iter;
class A
{
private:
int m_data[100];
int m_length;
public:
A();
void append(int);
A_iter begin();
A_iter end();
int operator[](int x) const;
};
class A_iter
{
private:
A* m_a;
int m_pos;
public:
A_iter(A* a,int p);
void operator++();
bool operator==(A_iter o) const;
bool operator!=(A_iter o) const;
int operator*() const;
};
int A_iter::operator*() const
{
return ((*m_a)[m_pos]);
}
bool A_iter::operator!=(A_iter o) const
{
return !(*this==o);
}
bool A_iter::operator==(A_iter o) const
{
return m_a==o.m_a && m_pos==o.m_pos;
}
A_iter::A_iter(A* a,int p)
{
m_a = a;
m_pos = p;
}
void A_iter::operator++()
{
m_pos++;
}
A::A()
{
m_length = 0;
}
void A::append(int x)
{
m_data[m_length++] = x;
}
A_iter A::begin()
{
return A_iter(this,0);
}
int A::operator[](int x) const
{
return m_data[x];
}
A_iter A::end()
{
return A_iter(this,m_length);
}
int main()
{
A a;
a.append(3);
a.append(4);
a.append(5);
for(auto it=a.begin();it!=a.end();++it)
{
cout<<*(it)<<endl;
}
unordered_map<int,int> m;
m.insert({1,2});
m.insert({3,4});
m.insert({5,6});
for(auto& [k,v]:m)
{
cout<<k<<" "<<v<<endl;
}
}