2015-09-19 71 views
-1

穿越总之我的问题,在“unordered_map”我会加入一对,名称以数字,并将其发送给一个函数。 (功能不要紧它做什么。)于是我将增加的另一件事到图形的地图,但我希望能够穿越到我添加到列表中的下一件事,因为我想扔标记的名字进入功能。C++,如何通过unordered_map

下面是一些代码

unordered_map<string,int> graph; 
unordered_map<string,int>:: iterator it; 
using namespace std; 

int main(){ 
    string name; 
    graph.insert(pair<string,int>("Sue",4));  
    it=graph.begin(); 
    name = it -> first; //name is equal to "Sue" 
    function(name); 
    graph.insert(pair<string,int>("Mark",83)); 
    it++ // this will not work 
    name = it -> first; //this will not end up equaling to "Mark" 
    function(name); 
    } 

++it不行,倒退--it,没有工作过。

那么有没有人有一个解决方案,我可以倒退得到name = it -> firstMark

注:(我会做这个方法太多次,因为它会进入一个循环)

+0

你说的“接下来的事情”是什么意思?接下来按什么顺序? –

+0

@TemplateRex我所做的唯一事情就是编辑文本。我从来没有(永远)删除或考虑删除标签。 (如果这样的事情发生的情况是不情愿还是你错) – Ziezi

+0

@simplicisveritatis好,编辑历史表明,你删除它,但没有问题,如果它是偶然! – TemplateRex

回答

3

对于unordered_map,它不能保证以后其他项目插入一个项目,也将后存储该项目。这就是无序地图的含义。

在这种情况下,你的运气了:在std::hash<std::string>密谋让“苏”来“标记”和it++graph.end()it->first被提领此,有内存错误之后。

,如果您使用有序map<string, int>和“标记”之后插入“苏”(或者你可以使用std::greater为“苏”后map比较你原来的“马克”的顺序),然​​后顺序元素就是你所期望的。

#include <unordered_map> 
#include <map> 
#include <iostream> 

using namespace std; 
map<string,int> graph; 
map<string,int>:: iterator it; 

int main() 
{ 
    string name; 
    graph.insert(pair<string,int>("Mark",4));  
    it=graph.begin(); 
    name = it -> first; //name is equal to "Sue" 
    std::cout << name; 
    graph.insert(pair<string,int>("Sue",83)); 
    it++ ;// this will not work 
    name = it -> first; //this will not end up equaling to "Mark" 
    std::cout << name; 
} 

Live Example

-1

我想这是因为当你调用Begin()产生的迭代器值。

在一些其他语言(C#)如果一个IEnumerable(例如List),而一个IEnumerator(亦称迭代)的变化是活动的,则Enumerator变为无效 和以下IEnumerator::MoveNext()将引发InvalidOperationException
看到MSDN Article on IEnumerator.MoveNext Method()

而且This article on CPPReference状态:

如果出现换汤不换药由于插入,所有迭代器无效。否则迭代器不受影响。引用不会失效。仅当新的元素数量等于或大于max_load_factor()* bucket_count()时才会重新散列。