Prashant Shubham Prashant Shubham - 3 months ago 12
C++ Question

Adding pair in set

I am trying to insert pair of int and string in my set. What i am trying to do is implement a hash map using sets, I am storing the number and its corresponding string using store function and then retrieving the string using retrieve. Please suggest what is the problem and is there any way it can be done more efficiently. The error is in store function. I have not written main function as its just taking input and calling the functions.

typedef pair<int, string> pairs;
pairs p;
set<pairs> s;
set<pairs>::iterator it;
int i=0;

void store(int num,string s)
{
p[i].first=num; //error is while I am using the pair to store the string
p[i].second=s;
s.insert(p[i]);
i++;
}

string retrieve(int num)
{
for(it=s.begin();it!=s.end();++it)
{
pairs m = *it;
if(m.first==num)
{
return m.second;
}
}
}


My error:

error: no match for ‘operator[]’ (operand types are ‘pairs {aka std::pair<int, std::basic_string<char> >}’ and ‘int’)
p[i].first=num;

Answer

pairs is a type alias for pair<int, string>. std::pair does not have an operator[] overload.

Assuming you want pairs to represent a collection of pairs, you need to make your pairs a container (e.g. a vector or an array).

As Martin Bonner noted in the comment, the symbol s inside store refers to the string s parameter. Change it to avoid clashing with set s's identifier.

typedef pair<int, string> pairs[100];
pairs p;

void store(int num, string str) 
{    
    p[i].first=num;  
    p[i].second=str;
    s.insert(p[i]);
    i++;   
}