今天看到有人在问这个问题,写了下代码,标准库分离了算法和数据结构,按照这个框架写程序确实比较方便,个人认为熟读和透彻理解标准库源码是每个想成为资深c++程序员的必修课,就框架结构而论,stl很好的分离了算法和数据结构,就算法而论,标准库里有很多常见算法的经典实现,所以有非常高的研究价值。
#include <iostream>
#include <stddef.h>
#include <stdlib.h>
#include <string>
#include <iterator>
#include <algorithm>
#include <vector>
using namespace std;
template <typename InputIterator1, typename InputIterator2, typename OutputIterator>
OutputIterator delete_intersection(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, OutputIterator dest)
{
while (first1 != last1 && first2 != last2) {
if (*first1 > *first2) {
*dest = *first2;
++first2;
++dest;
} else if (*first1 < *first2) {
*dest = *first1;
++first1;
++dest;
} else {
++first1;
++first2;
}
}
for (;first2 != last2; ++first2) *dest = *first2;
return dest;
}
int main() {
int a[] = {1,1,2,2,5,6,9,9};
int b[] = {1,2,3,4,4,6,7,8,9,9,9,10};
vector<int> vc;
delete_intersection(a, a + sizeof(a)/sizeof(a[0]), b, b + sizeof(b)/sizeof(b[0]), back_inserter(vc));
std::copy(a, a + sizeof(a)/sizeof(a[0]), ostream_iterator<int>(cout, ","));
cout << endl;
std::copy(b, b + sizeof(b)/sizeof(b[0]), ostream_iterator<int>(cout, ","));
cout << endl;
std::copy(vc.begin(), vc.end(), ostream_iterator<int>(cout, ","));
cout << endl;
::system("PAUSE");
return EXIT_SUCCESS;
}
posted on 2009-03-05 18:56
许海斌 阅读(1070)
评论(4) 编辑 收藏 引用