今天做一個題目:輸入一個integer數組和一個integer型的target,然後輸出數組中兩個元素s1、s2,使s1和s2相加等於target。我做的方法是先排序,然後用一個指針指向數組頭部,一個指針指向數組尾部,依次判斷兩者相加是否等於target。若大於target,則尾指針向前移動;若小於target,則頭指針向前移動;若相等,則返回,直到兩個指針相等。
剛開始的代碼如下:
#include<iostream>
#include<vector>
#include<iterator>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<vector<int>::iterator, vector<int>::iterator> iterator_pair;
iterator_pair TwoSum(vector<int> coll, const int sum)
{
vector<int>::iterator first = coll.begin();
vector<int>::iterator last = --coll.end();
int temp;
while (first != last)
{
temp = *first + *last;
if (temp > sum)
last--;
else if (temp < sum)
first++;
else
break;
}
temp = *first + *last;
iterator_pair p(coll.end(), coll.end());
if (temp == sum)
{
p.first = first;
p.second = last;
}
return p;
}
int main()
{
vector<int> array;
array.push_back(7);
array.push_back(3);
array.push_back(8);
array.push_back(9);
array.push_back(12);
array.push_back(20);
array.push_back(76);
sort(array.begin(), array.end());
copy(array.begin(), array.end(), ostream_iterator<int>(cout, " "));
iterator_pair p;
p = TwoSum(array, 16);
cout << endl;
cout << *p.first << " " << *p.second << endl;
system("pause");
return 0;
}
結果出現錯誤,調試發現p從函數返回後其內容爲垃圾值,而在函數中運行正常。最後調試發現array和coll不一樣,終於發現問題了!原來我一直將vector當成數組看待,所以在函數中就直接傳值,可是vector及其他各容器及迭代器等都是以類的形式定義的,所以在這兒傳值的話會調用複製構造函數構造一個臨時對象,在函數返回時這個臨時對象會被銷燬,所以p也就指向了垃圾值。看來自己還是要多學習STL方面的知識,不能想當然的把兩個相似的東西同等看待。在函數中應該傳vector指針或引用,下面是改正後的代碼:
#include<iostream>
#include<vector>
#include<iterator>
#include<map>
#include<algorithm>
using namespace std;
typedef pair<vector<int>::iterator, vector<int>::iterator> iterator_pair;
iterator_pair TwoSum(vector<int> coll, const int sum)
{
vector<int>::iterator first = coll.begin();
vector<int>::iterator last = --coll.end();
int temp;
while (first != last)
{
temp = *first + *last;
if (temp > sum)
last--;
else if (temp < sum)
first++;
else
break;
}
temp = *first + *last;
iterator_pair p(coll.end(), coll.end());
if (temp == sum)
{
p.first = first;
p.second = last;
}
return p;
}
int main()
{
vector<int> array;
array.push_back(7);
array.push_back(3);
array.push_back(8);
array.push_back(9);
array.push_back(12);
array.push_back(20);
array.push_back(76);
sort(array.begin(), array.end());
copy(array.begin(), array.end(), ostream_iterator<int>(cout, " "));
iterator_pair p;
p = TwoSum(array, 16);
cout << endl;
cout << *p.first << " " << *p.second << endl;
system("pause");
return 0;
}