今天看到有人在問這個(gè)問題,寫了下代碼,標(biāo)準(zhǔn)庫分離了算法和數(shù)據(jù)結(jié)構(gòu),按照這個(gè)框架寫程序確實(shí)比較方便,個(gè)人認(rèn)為熟讀和透徹理解標(biāo)準(zhǔn)庫源碼是每個(gè)想成為資深c++程序員的必修課,就框架結(jié)構(gòu)而論,stl很好的分離了算法和數(shù)據(jù)結(jié)構(gòu),就算法而論,標(biāo)準(zhǔn)庫里有很多常見算法的經(jīng)典實(shí)現(xiàn),所以有非常高的研究價(jià)值。
#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)
評(píng)論(4) 編輯 收藏 引用