Sha*_*ter 4 c++ containers iterator std-pair
如果我有一个容器(vector,list等),其中每个元素都是a std::pair,是否有一种简单的方法来迭代每对元素的每个元素?
即
std::vector<std::pair<int,int> > a;
a.push_back(std::pair(1,3));
a.push_back(std::pair(2,3));
a.push_back(std::pair(4,2));
a.push_back(std::pair(5,2));
a.push_back(std::pair(1,5));
Run Code Online (Sandbox Code Playgroud)
然后能够迭代该值:1,3,2,3,4,2,5,2,1,5?
类似地,什么类型的仿函数/函数会返回一个容器(相同类型),如上所述的对元素的扁平列表?
对于你的第一个,你必须创建自己的迭代器类,它将一个表示内部对位置的标志与一个container<pair>迭代器配对
对于第二个,它更容易,虽然要像你想要的那样一般(相同类型的容器)你需要一个模板typedef.这是仅矢量:
template <class V>
std::vector<V> flatten_pairs(std::vector<std::pair<V,V> > const& a) {
typedef std::vector<std::pair<V,V> > A;
std::vector<V> ret;
for (typename A::const_iterator i=a.begin(),e=a.end();i!=e;++i) {
ret.push_back(i->first);
ret.push_back(i->second);
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
以下是伪造模板typedef的方法:
template <class C>
struct same_container;
template <class V>
struct same_container<std::vector<V> > {
template <class W> struct rebind { typedef std::vector<W> type; };
};
template <class V>
struct same_list<std::list<V> > {
template <class W> struct rebind { typedef std::list<W> type; };
};
template <class C>
typename same_container<C>::rebind<typename C::value_type::first_type>::type
flatten_pairs(C const& a);
Run Code Online (Sandbox Code Playgroud)
以下代码将根据需要打印所有值:
for ( size_t x = 0; x < a.size(); ++x ) {
cout << a[x].first << "," << a[x].second << ",";
}
Run Code Online (Sandbox Code Playgroud)
我更喜欢这种简单的方法,而不是创建自定义迭代器.