如何访问地图
How to access map?
我不知道如何访问结构Student内部的映射我查到的一些例子说->第一个->第二个但这不会编译。
如何访问结构中的映射?或者操作员过载是错误的?
错误显示‘->’ has non-pointer type
struct Student{
string id;
map<string, double> scores;
};
ostream& operator<<(ostream& os, const Student& g){
return os << g.id << 'n' << g.scores->first << 'n' << g.scores->second ;
}
istream& operator >>(istream& is, Student& g){
return is >> g.id >> g.scores->first >> g.scores->second;
}
int main() {
vector<Student> g_vec;
Student grades;
while(cin >> gd)
g_vec.push_back(grades);
for (auto& g : g_vec)
cout << g << endl;
}
.
和->
之间的主要区别在于开头的对象类型。当您有对象时使用.
,当您有指向对象的指针时使用->
如果你这样定义学生
Student erik = ...
你会得到这样的erik的id:
erik.id
如果你这样定义erik:
Student* erik = ...
你会得到这样的身份证:
erik->id
这就是错误的意思
但您还有另一个问题,因为first
和second
不是为映射定义的,而是为映射元素定义的。您需要在映射中进行迭代,以便执行您想要的操作。我想像这样的东西会更好
os << g.id << 'n'
for (auto& it : g.scores) {
os<< it.first << it.second << 'n' ;
}
我还没有理解这个问题。如果你给我们看一下样品输出,会更详细。对不起,如果我错了,我找不到你什么时候停止读取数据?
您需要使用pair来插入映射和遍历,您应该使用迭代器。希望这有帮助:
ostream& operator<<(ostream& os, const Student& g){
//here you need to write for loop to traverse the entire map. I am printing only last ele. .
map<string,double>::const_iterator myit = g.scores.end();
os << g.id << 'n' << myit->first << 'n' << myit->second ;
return os;
}
istream& operator >>(istream& is, Student& g){
pair<string,double> mypair;
is >> g.id >> mypair.first >> mypair.second;
g.scores.insert(mypair);
return is;
}
相关文章:
- 如何包装(撰写)增强 hana 地图并访问括号运算符(运算符 [])?
- 以C++访问矢量中的地图元素
- 如何访问具有地图的2D矢量?
- 如何从地图访问数组的元素?
- 如何访问整个地图的值
- std::在地图上查找无法正常工作并循环访问地图的键和值
- 无法循环访问标准::地图
- 尝试访问地图中元素时的错误
- 简单的 CPP 地图存储和访问无法按预期工作
- 从地图擦除后访问指针
- 从地图访问对象会导致新对象C 的实例化
- 在C++中访问和插入地图的地图(嵌套地图)
- 无法访问/存储地图中的游戏状态对象
- 如何从公共函数成员访问地图私有成员
- 以对为键访问地图
- 如何避免地图访问的常量投射?
- C++地图访问和迭代所花费的时间
- C++加快地图访问速度
- 在c++地图访问上的segfault
- 包装地图访问,聪明还是愚蠢