2017-02-16 47 views
1

我想使用迭代器将Xmap插入Ymap。使用迭代器将值插入嵌套映射

typedef map<float, int> Xmap; 
typedef map<float, Xmap> Ymap; 

Xmap Xcoordinate; 
Ymap Ycoordinate; 

int Id; 
float x; 
float y; 
char c; 

    while (line >> Id >> c >> x >> c >> y) 
    { 
     Ymap::iterator iy = Ycoordinate.find(y); 
     if (iy == Ycoordinate.end()) 
      Ycoordinate.insert(pair<float, Xmap>(y, Xmap())); 
     iy->second.insert(pair<float, int>(x, Id)); 
    } 

我有一个文本文件中的Id,x,y。 c是要照顾逗号的。

如何使用迭代器将x和Id插入到嵌套的Xmap中?

谢谢!

+0

那么,你已经_did_在这一行插入你的点到嵌套'Xmap':'iy-> second.insert(对(x,Id));'。请注意,每个'Ymap'的条目隐含地包含'Xmap',所以您不必自己定义它们。 'Xmap Xcoordinate;'定义了一个完全独立的独立的'Xmap',它完全不了解'Ycoordinate'或'Ymap'。 – yeputons

回答

0
Ymap::iterator iy = Ycoordinate.find(y); 
    if (iy == Ycoordinate.end()) 
     Ycoordinate.insert(pair<float, Xmap>(y, Xmap())); 
    iy->second.insert(pair<float, int>(x, Id)); 

如果find()没有找到y,并且iy是结束迭代器值,第一insert()插入一个新进入的第一个地图。

这很好,很花哨,但由于新值插入地图这一事实,不会自动更改iy以引用新插入的值。因此,iy仍然是end(),就像确定的if语句一样,而iy->second最终取消了引用结束迭代器值,导致未定义的行为。解决这个问题

一种方法是简单地设置iy

if (iy == Ycoordinate.end()) 
     iy=Ycoordinate.insert(pair<float, Xmap>(y, Xmap())).first; 

见地图的insert()方法的文档,特别是返回值,以获取更多信息。

但是,所有这些看起来完全没有必要,还有一堆额外的工作。这里发生的所有事情,从它的外观来看,就是如果密钥不存在,那么将默认初始化值插入到映射中。

为什么要重新发明轮子?这就是operator[]是:

while (line >> Id >> c >> x >> c >> y) 
{ 
    Ycoordinate[y].insert(pair<float, int>(x, Id)); 
} 

或者,甚至:

while (line >> Id >> c >> x >> c >> y) 
{ 
    Ycoordinate[y][x]=Id; 
} 

这显然要简单得多。但是,如果你想学习如何“使用迭代器将值插入到地图中”,那么在逻辑上就需要阅读std::map::insert的文档,该文档会告诉你它是如何工作的。如果你这样做,你应该立即明白,你仍然可以简化你的逻辑:

while (line >> Id >> c >> x >> c >> y) 
{ 
    Ycoordinate.insert(pair<float, Xmap>(y, Xmap())).first 
     ->second.insert(pair<float, int>(x, Id)); 
} 

这仍然是,在技术上,使用迭代器因为这是的东西,insert()的回报之一。

+0

非常感谢! – Chalupa