正确答案是Some programmer dude。好主意。
我在 cppreference.com C++ 文档中找到了 set_intersection 实现。我按照他的建议做了一些修改,效果很好。
下面是展示其工作原理的示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
template<class Value, class InputIt1, class InputIt2, class OutputIt>
OutputIt my_intersection(InputIt1 first1, InputIt1 last1,
InputIt2 first2, InputIt2 last2,
OutputIt d_first)
{
auto start1 = first1;
auto start2 = first2;
while (first1 != last1 && first2 != last2) {
if (*first1 < *first2) {
first1++;
continue;
}
if (*first2 == *first1) {
pair<Value, vector<size_t>> item;
vector<size_t> positions;
positions.push_back (distance (start1, first1));
positions.push_back (distance (start2, first2));
item.first = *first1;
item.second = positions;
*d_first++ = item;
*first1++;
}
first2++;
}
return d_first;
}
int main()
{
vector<int> v1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<int> v2 = { 2, 4, 6, 8, 30, 50, 70, 90, 100, 1000 };
vector<pair<int, vector<size_t>>> intersection;
my_intersection<int> (
v1.begin (), v1.end (),
v2.begin (), v2.end (),
back_inserter (intersection)
);
for (auto &item : intersection) {
cout << item.first << ":";
for (auto &position : item.second) {
cout << " " << position;
}
cout << endl;
}
}
输出:
2: 1 0
4: 3 1
6: 5 2
8: 7 3