std :: set_intersection的struct对象

时间:2018-03-08 14:58:18

标签: c++ stl set containers const

我尝试使用dist来获取两个集合的交集,这两个集合存储名为std::set_intersection的结构类型的对象。我希望结果存储在另一个set<dist>

但是,编译器会出现以下错误:

In file included from /usr/include/c++/5/algorithm:62:0,
             from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
             from /home/kirill/CLionProjects/contest/main.cpp:1:
/usr/include/c++/5/bits/stl_algo.h: In instantiation of ‘_OutputIterator std::__set_intersection(_InputIterator1, _InputIterator1, _InputIterator2, _InputIterator2, _OutputIterator, _Compare) [with _InputIterator1 = std::_Rb_tree_const_iterator<dist>; _InputIterator2 = std::_Rb_tree_const_iterator<dist>; _OutputIterator = std::_Rb_tree_const_iterator<dist>; _Compare = __gnu_cxx::__ops::_Iter_less_iter]’:
/usr/include/c++/5/bits/stl_algo.h:5122:48:   required from ‘_OIter std::set_intersection(_IIter1, _IIter1, _IIter2, _IIter2, _OIter) [with _IIter1 = std::_Rb_tree_const_iterator<dist>; _IIter2 = std::_Rb_tree_const_iterator<dist>; _OIter = std::_Rb_tree_const_iterator<dist>]’
/home/kirill/CLionProjects/contest/main.cpp:65:73:   required from here
/usr/include/c++/5/bits/stl_algo.h:5076:16: error: passing ‘const dist’ as ‘this’ argument discards qualifiers [-fpermissive]
      *__result = *__first1;
            ^
/home/kirill/CLionProjects/contest/main.cpp:26:8: note:   in call to ‘dist& dist::operator=(const dist&)’
 struct dist {
    ^
CMakeFiles/contest.dir/build.make:62: recipe for target 'CMakeFiles/contest.dir/main.cpp.o' failed
make[3]: *** [CMakeFiles/contest.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/contest.dir/all' failed
make[2]: *** [CMakeFiles/contest.dir/all] Error 2
CMakeFiles/Makefile2:79: recipe for target 'CMakeFiles/contest.dir/rule' failed
make[1]: *** [CMakeFiles/contest.dir/rule] Error 2
Makefile:118: recipe for target 'contest' failed
make: *** [contest] Error 2

这是一个结构定义:

struct dist {
    int x_dist;
    int y_dist;

    bool operator<(dist const & b) const {
        return tie(x_dist, y_dist) < tie(b.x_dist, b.y_dist);
    }
};

我在这里调用set_intersection方法:

#define all(c) (c).begin(), (c).end()
void intersection_taxi_fan() {
    intersection.clear();
    set_intersection(all(taxi_dist), all(fan_dist), intersection.begin());
}

1 个答案:

答案 0 :(得分:5)

您不能将intersection.begin()作为set_intersection的参数传递,因为它是const值的迭代器

  

*注意:设置中的所有迭代器都指向const元素。   [来自http://www.cplusplus.com/reference/set/set/]

set_intersection修改此迭代器指向的值(在set_intersection算法的下面代码段代码中的第[1]行)。

    else if (*first2<*first1) ++first2;
else {
  *result = *first1;   // [1] try modifying const value
  ++result; ++first1; ++first2;
}

无法修改Const对象。

您可以使用std::inserter将元素插入intersection

    set_intersection(all(taxi_dist), all(fan_dist), inserter(intersection, intersection.end()));