我试图获得两个集合的交集,使用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());
}发布于 2018-03-08 15:17:59
不能将intersection.begin()作为set_intersection的参数传递,因为它是对const值的迭代器。
*注意:在const元素的集合点上的所有迭代器。from [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;
}对象不能被修改。
可以使用std::inserter将元素插入到intersection集中。
set_intersection(all(taxi_dist), all(fan_dist), inserter(intersection, intersection.end()));https://stackoverflow.com/questions/49176116
复制相似问题