源代碼
#include <iostream>
#include <list>
#include <iterator> // for std::prev
using namespace std;
int main()
{
? ? int target = 9;
? ? list<int> l{ 2, 3, 4, 6, 8 };
? ? l.sort(); // 確保列表是排序的,因為雙指針法要求輸入是有序的
? ? auto itB = l.begin(); // 迭代器指向列表的第一個元素
? ? auto itE = prev(l.end()); // 迭代器指向列表的最后一個元素
? ? list<int> returnlist{};
? ? while (itB != itE)
? ? {
? ? ? ? int sum = *itB + *itE;
? ? ? ? if (sum > target) // 大于去大
? ? ? ? {
? ? ? ? ? ? --itE;
? ? ? ? }
? ? ? ? else if (sum < target) // 小于去小
? ? ? ? {
? ? ? ? ? ? ++itB;
? ? ? ? }
? ? ? ? else // 找到了
? ? ? ? {
? ? ? ? ? ? returnlist.push_back(*itB);
? ? ? ? ? ? returnlist.push_back(*itE);
? ? ? ? ? ? break;
? ? ? ? }
? ? }
? ? if (!returnlist.empty())
? ? {
? ? ? ? cout << "Found numbers: [";
? ? ? ? bool first = true;
? ? ? ? for (int num : returnlist)
? ? ? ? {
? ? ? ? ? ? if (!first) cout << ", ";
? ? ? ? ? ? cout << num;
? ? ? ? ? ? first = false;
? ? ? ? }
? ? ? ? cout << "]" << endl;
? ? }
? ? else
? ? {
? ? ? ? cout << "No pair found that adds up to " << target << "." << endl;
? ? }
? ? return 0;
}