Could you please
- describe in details, what your program is supposed to do
- provide inputs that cause a problem for you and also provide what the expected outcome you think should be.
Without this, I'll go with my own assumptions what the problem may be.
I believe what you're trying to do is ask the user to provide an array and a number and the program tries to find two numbers in this array where the sum of those equals to number. The program prints the indices of these numbers.
If you remove the sorting (sort(a,a+n);) your code should return the right indices. However, it will not find all the possible index pairs. For that, you must not break the loop when you find a working solution.
I would also recommend printing to the user what they should do before you ask for input and using better variable names.
All in all, your code could look something like this after some fix-up:
#include <iostream>
#include <unordered_map>
using namespace std;
void createArray(int * a, int n)
{
for(int i = 0; i < n; i++)
{
int data;
cout << "data[" << i << "] = ";
cin >> data;
a[i] = data;
}
}
void solution(int * a, int n, int toSum)
{
unordered_map<int, int> exist;
for (int i = 0; i < n; i++)
{
exist[a[i]] = i;
}
cout << "Index pairs successfully summing indexed elements to " << toSum << ":" << endl;
for (int i = 0; i < n; i++)
{
int toFind = toSum - a[i];
unordered_map<int, int>::const_iterator itemIterator = exist.find(toFind);
if (itemIterator != exist.end())
{
cout << '\t' << i << " " << itemIterator->second << endl;
}
}
}
int main()
{
int arraySize;
cout << "Array size (0 to quit) = ";
cin >> arraySize;
while (arraySize != 0)
{
int array[arraySize];
createArray(array, arraySize);
int sum;
cout << "sum = ";
cin >> sum;
solution(array, arraySize, sum);
cout << "Array Size (0 to quit) = ";
cin >> arraySize;
}
}