简体   繁体   English

transform_iterator与std :: iterators不兼容?

[英]transform_iterator not compatible with std::iterators?

I'm having problems using boost::transform_iterator s where "ordinary" iterators are expected. 我在使用boost::transform_iterator遇到问题,在这里需要“普通”迭代器。 For instance, I want to add all keys from a map to a set. 例如,我想将地图中的所有键添加到集合中。 I wrote the following short snippet: 我写了以下简短代码段:

template <typename K, typename V>
struct map_keys {
    typedef const K& result_type;
    const K& operator()(const std::pair<K,V>& kvp) const {
        return kvp.first;
    }
};

int main() {
    std::map<int, double> my_map;
    std::set<int> my_set;
    my_map[1]=1.2;
    my_map[2]=2.4;
    my_map[4]=4.1;
    my_map[6]=12.2;
    my_map[123]=3;
    typedef map_keys<int, double> mk;
    auto b = boost::make_transform_iterator(my_map.begin(), mk()),
        e = boost::make_transform_iterator(my_map.end(), mk());
    my_set.insert(b,e);
    return 0;
}

After the insert , my_set contains a single value, -858993460 or 0xcccccccc . insertmy_set包含单个值-8589934600xcccccccc Why? 为什么? If I print *b in a loop, all the values are printed as expected. 如果我循环打印*b ,则所有值将按预期打印。

Ok, solved it myself suddenly. 好吧,我自己突然解决了。 The problem is the typedef result_type (which is not mentioned in the documentation, but unless I have it, the code does not compile ( result_type is not a member of map_keys<K,V> )). 问题是typedef result_type (在文档中未提及,但是除非我拥有它,否则代码不会编译( result_type不是map_keys<K,V>的成员))。 If I instead typedef it as 如果我改用typedef作为

typedef K result_type;

It works. 有用。 I suppose as it was written earlier, it returned the address of something? 我想像它先前写的那样,它返回了某个地址?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM