在集合中添加对

Pra*_*ham 0 c++ set std-pair

我正在尝试在我的集合中插入一对 int 和 string。我想要做的是使用集合实现哈希映射,我使用存储函数存储数字及其对应的字符串,然后使用检索检索字符串。请提出问题是什么,有什么方法可以更有效地完成。错误出在 store 函数中。我没有编写 main 函数,因为它只是接收输入和调用函数。

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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

我的错误:

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

Vit*_*meo 5

pairs是 的类型别名pair<int, string>std::pair没有operator[]过载

假设您想pairs表示一组对,您需要制作pairs一个容器(例如 avector或 an array

正如Martin Bonner在评论中所指出的,s里面的符号store是指string s参数。更改它以避免与set s的标识符发生冲突。

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++;   
}
Run Code Online (Sandbox Code Playgroud)