为一对容器的第一个元素提供一个迭代器 [英] Providing an iterator for the first element of a container of pairs

查看:129
本文介绍了为一对容器的第一个元素提供一个迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个装满了成对的容器。我想使用STL泛型算法迭代它(在我的情况下,它将是inner_product,但将其视为一般问题)。
我正在使用的算法需要迭代器第一个和最后一个。我可以提供特殊的迭代器首先和最后的迭代,而不是迭代对,但每对迭代器的第一个元素?

我知道我可以手动完成它,提供一个手工制作的函数对象,它将作为标准容器迭代器的包装器,将其引用到对的第一个成员我想这对我来说也有一个聪明的一行。它会是什么?

解决方案

我环顾四周,发现 boost :: transform_iterator 。我已经提出了这个代码。令人惊讶的是它的工作效果如何:

  #include< map> 
#include< algorithm>
#include< iostream>
#include< string>
#include< iterator>
#include< boost / iterator / transform_iterator.hpp>
#include< boost / bind.hpp>
#include< boost / function.hpp>

int main(){
typedef std :: map< std :: string,int> :: value_type value_type;
std :: map< std :: string,int>一个;
a [one] = 1;
a [two] = 2;

//返回第二个元素
boost :: function< int(value_type&)> f = boost :: bind(& value_type :: second,_1);
std :: copy(boost :: make_transform_iterator(a.begin(),f),
boost :: make_transform_iterator(a.end(),f),
std :: ostream_iterator< int>(std :: cout,));




$ p
$ b

它正在打印1 2 到标准输出。


I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem). The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on the first element of each pair?

I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?

解决方案

I've looked around and found boost::transform_iterator. I've come up with this code. Surprising how well it works:

#include <map>
#include <algorithm>
#include <iostream>
#include <string>
#include <iterator>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>

int main() {
    typedef std::map<std::string, int>::value_type value_type;
    std::map<std::string, int> a;
    a["one"] = 1;
    a["two"] = 2;

    // returns the second element 
    boost::function<int(value_type&)> f = boost::bind(&value_type::second, _1);
    std::copy(boost::make_transform_iterator(a.begin(), f), 
              boost::make_transform_iterator(a.end(), f),
              std::ostream_iterator<int>(std::cout, " "));

}

It's printing "1 2 " to the standard output.

这篇关于为一对容器的第一个元素提供一个迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆