我正在做一个家庭作业,它应该打印总和为val的所有整数对。我到目前为止已完成,除了它打印重复值(即(3,1)和(1,3)的值添加到4)。如何删除这些重复的值对?
#include <iostream>
#include <map>
#include <vector>
using namespace std;
void printPairs( vector<int> numbers, int val){
int i;
int temp;
map<int,int>valMap;
for(i = 0; i < numbers.size(); i++){
temp = val - numbers[i];
if(temp >= 0 && valMap[temp] == 1){
printf("Pair of integers that sum to val %d is (%d, %d) \n", val, numbers[i], temp);
}
valMap[numbers[i]] = 1;
}
}
int main(int argc, char *argv[]) {
vector <int> v(11);
v[0]=1;
v[1]=2;
v[2]=3;
v[3]=4;
v[4]=5;
v[5]=6;
v[6]=7;
v[7]=1;
v[8]=2;
v[9]=3;
v[10]=4;
printPairs(v,7);
system("PAUSE");
}
答案 0 :(得分:0)
这种打印功能的变种......
void printPairs( vector<int> numbers, int val){
int i, j;
map<int,int>valMap;
// build a map
for(i = 0; i < numbers.size() - 1; i++)
{
for(j = i; j < numbers.size(); j++)
{
if( (numbers[i] + numbers[j]) == val)
{
// use minimum value as a key, and max value as a value
valMap[ (numbers[i] < numbers[j])?numbers[i]:numbers[j] ] = (numbers[i] >= numbers[j])?numbers[i]:numbers[j];
}
}
}
// print all map's values
for(map<int,int>::iterator iter = valMap.begin(); iter !=valMap.end(); iter++)
{
printf("Pair of integers that sum to val %d is (%d, %d) \n", val, iter->first, iter->second);
}
}
...给出输出......
Pair of integers that sum to val 7 is (1, 6)
Pair of integers that sum to val 7 is (2, 5)
Pair of integers that sum to val 7 is (3, 4)