翻译C++;一小条 我正在研究从C++移植到java的框架,它的难度比我预期的要高,因为我对C++的了解不多。我偶然发现了一个我不太理解的片段。如果有人能告诉我标记的行是做什么的,那就太棒了 /** Heap data, stored as a vector */ std::vector< std::pair< _Tp, _Val > > data; /** Maps objects to their positions in the data vector */ std::map< _Tp, int> mapping; //I understand that this method takes a pair of type <_Tp, _Val> template <class _Tp, class _Val> void Heap<_Tp,_Val>::push(std::pair< _Tp, _Val > x) { int index=data.size(); //Here is where I run into trouble //I can't seem to figure out what this line is doing //I know it is inserting a Key-Value pair into the map //but why is .second being called? and what exactly is this if statement //checking? if (mapping.insert(std::make_pair(x.first,index)).second) { data.push_back(x); percolate_up(index); } } /**堆数据,存储为向量*/ std::vector数据; /**将对象映射到其在数据向量中的位置*/ 标准::映射映射; //我知道这个方法需要一对类型 模板 无效堆::推送(std::pairx) { int index=data.size(); //这就是我遇到麻烦的地方 //我似乎不明白这条线在干什么 //我知道这是在地图中插入一个键值对 //但是为什么要调用.second?这个if语句到底是什么 //检查? if(mapping.insert(std::make_pair(x.first,index)).second) { 数据。推回(x); 渗滤液(指数); } }

翻译C++;一小条 我正在研究从C++移植到java的框架,它的难度比我预期的要高,因为我对C++的了解不多。我偶然发现了一个我不太理解的片段。如果有人能告诉我标记的行是做什么的,那就太棒了 /** Heap data, stored as a vector */ std::vector< std::pair< _Tp, _Val > > data; /** Maps objects to their positions in the data vector */ std::map< _Tp, int> mapping; //I understand that this method takes a pair of type <_Tp, _Val> template <class _Tp, class _Val> void Heap<_Tp,_Val>::push(std::pair< _Tp, _Val > x) { int index=data.size(); //Here is where I run into trouble //I can't seem to figure out what this line is doing //I know it is inserting a Key-Value pair into the map //but why is .second being called? and what exactly is this if statement //checking? if (mapping.insert(std::make_pair(x.first,index)).second) { data.push_back(x); percolate_up(index); } } /**堆数据,存储为向量*/ std::vector数据; /**将对象映射到其在数据向量中的位置*/ 标准::映射映射; //我知道这个方法需要一对类型 模板 无效堆::推送(std::pairx) { int index=data.size(); //这就是我遇到麻烦的地方 //我似乎不明白这条线在干什么 //我知道这是在地图中插入一个键值对 //但是为什么要调用.second?这个if语句到底是什么 //检查? if(mapping.insert(std::make_pair(x.first,index)).second) { 数据。推回(x); 渗滤液(指数); } },c++,C++,此处使用的insert成员函数返回一个对,如果进行了插入,bool成员为true。因此,if语句将查看insert调用是否实际向映射添加了一条记录 P>当使用C++ +./p>时,您可能会发现引用标准库的文档是有用的。 insert成员函数返回一对,如果进行了插入,则其bool组件返回true;如果映射已包含一个元素,且该元素的键在排序中具有等效值,则返回false,其迭代器组件返回插入新元素或元素已位于的地址 因此,代码正在将一个元素添加到映射,如果元素不在那里,它会将数据推送到向量哦,好的

此处使用的
insert
成员函数返回一个
,如果进行了插入,
bool
成员为
true
。因此,
if
语句将查看
insert
调用是否实际向映射添加了一条记录

<> P>当使用C++ +./p>时,您可能会发现引用标准库的文档是有用的。
insert
成员函数返回一对,如果进行了插入,则其
bool
组件返回true;如果映射已包含一个元素,且该元素的键在排序中具有等效值,则返回false,其迭代器组件返回插入新元素或元素已位于的地址


因此,代码正在将一个元素添加到
映射
,如果元素不在那里,它会将数据推送到
向量

哦,好的,谢谢。我正在看的页面没有列出一对返回值..太糟糕了。我将不得不对我从中获取信息的网站更加小心。thanks@Hunter-退回一对不是“标准”行为。我想你正在使用VC++?!依靠向量插入对的返回是不可移植的。因此,您正在查看的页面可能没有错误,只是与您的编译器不匹配。@Michael:不是向量插入,而是映射插入,并且返回对在C++11标准中存在,这在C++03中无效吗?@K-ballo-抱歉,是指映射。我不是语言律师,但我不认为C++03标准定义了一对的返回。在过去,从Win上的VC++到*nix上的gcc,我都遇到过这样的问题。请参阅以获取无效退货的示例。感谢您的评论,我在查看的页面上没有看到该退货类型。另外,谢谢你的链接