# c++ – Finding all pairs of elements in an array that sum to a target value using multiple pointers (follow up)

The previous question was not clear enough so I will try to clarify it more in this follow-up question.
I tried the multiple pointers technique to solve the problem that find pair of values that sums up to a target value.

We are assuming that:

• the array is already sorted.
• we are working with a static array of size 16 (testing purpose only).
• we are not working with actual pointers; because we don’t need them in this case (I think), I named the question on the algorithm’s
name only.
``````    #include <iostream>
#include <vector>
using namespace std;

struct result
{
int num1;
int num2;
result() {}

result(int num1, int num2)
: num1{ num1 }, num2{ num2 } {}
};

vector<result> mult_pt(int arr(), int target)
{
int p1 = 0;
int p2 = 15;
bool flag = false;
vector<result> res;
while (p1 <= p2)
{
if (arr(p1) + arr(p2) == target)
{

for (int k = 0; k < res.size() - 1; k++)
{
if (res.size() == 0)
res.push_back(result(arr(p1), arr(p2)));
else if (res(k).num1 != arr(p1) && res(k).num2 != arr(p2))
{
flag = false;
}
else flag = true;
}
if(flag) res.push_back(result(arr(p1), arr(p2)));
p1++;
}
else if (arr(p1) + arr(p2) < target)
{
p1++;
continue;
}
else if (arr(p1) + arr(p2) > target)
{
p2--;
for (int i = p1; i >=0; i--)
{
if (arr(i) + arr(p2) == target)
{
res.push_back(result(arr(p1), arr(p2)));
}
else if (arr(i) + arr(p2) > target)
{
continue;
}
else break;
}
}
}
return res;
}

int main ()
{
int array(16) = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
vector <result> res = mult_pt(array, 19);
for (int j = 0; j < res.size(); j++)
{
cout << "( " << res(j).num1 << " , " << res(j).num2 << " )" << endl;
}
return 0;
}

``````

The output should be like:

``````( 4 , 15 )
( 5 , 14 )
( 6 , 13 )
( 7 , 12 )
( 8 , 11 )
( 9 , 10 )
( 10 , 9 )
``````

You can check the previous post here.