今天看到有人在問這個問題,寫了下代碼,標準庫分離了算法和數據結構,按照這個框架寫程序確實比較方便,個人認為熟讀和透徹理解標準庫源碼是每個想成為資深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
許海斌 閱讀(1081)
評論(4) 編輯 收藏 引用