VaioIsBorn
VaioIsBorn

Reputation: 7903

No match for call to '(std::pair<unsigned int, unsigned int>) (unsigned int&, unsigned int)'

I don't know what's wrong with the follwing code, it should read numbers and put their value with the position together in a vector of pairs and then sort them and print out the positions. I removed the part with sort - i thought the problem was there, but i received an error on compilation again.

#include <iostream>                                                                                                           
#include <vector>                                                                                                             
#include <algorithm>                                                                                                          
#include <utility>                                                                                                            
using namespace std;                                                                                                          

int main(void)
{
        unsigned int n,d,a[65],b[65],s,i,j,t,us=0;
        pair<unsigned int,unsigned int> temp;
        vector< pair<unsigned int,unsigned int> > v;
        cin >> n;
        for(i=0;i<n;i++)
        {
                cin >> t;
                temp(t, i+1);
                v.push_back(temp);
        }
        cin >> d;
        for(i=0;i<d;i++) cin >> a[i] >> b[i];
        for(i=0;i<v.size();i++)
        {
                cout << v[i].first << " -- " << v[i].second << endl;
        }
        return 0;
}

Please tell me where is the problem. Thanks.

Upvotes: 1

Views: 6664

Answers (2)

Binary Worrier
Binary Worrier

Reputation: 51711

The problem is temp(t, i+1);

You need to set the first and second manually

temp.first = t;
temp.second = i + 1;

Alternatively you can declare temp inside the loop (probably what I'd do).

for(i=0;i<n;i++) 
{ 
    cin >> t; 
    pair<unsigned int,unsigned int> temp(t, i+1); 
    v.push_back(temp); 
} 

Or a second alternate, use the make_pair helper function, and do away with temp completely (thanks to KennyTM for the reminder)

for(i=0;i<n;i++) 
{ 
    cin >> t; 
    v.push_back(make_pair(t, i+1)); 
} 

Hope this helps

Upvotes: 2

Kylotan
Kylotan

Reputation: 18449

It's generally bad form to create a variable outside of a loop and re-use it many times in the loop, if the only place you use it is in that loop. Only do this if the construction cost is high and it's cheaper to re-assign than to re-create. Generally C++ variables should be declared in the scope they are used, to make it easier to read each part of the program and to be able to re-factor it later.

In your case, I would delete the reference to temp entirely, and change the push_back call to v.push_back(make_pair(t, i+1)).

Upvotes: 3

Related Questions