2014-05-13 67 views
1

我有这样的代码:Unordered_map迭代器抛出错误

int solution(int K, const vector<int> &A) { 
    int count=0,size,comp=0; 
    unordered_map<long,long> map; 

    size = A.size(); 
    if(size==0) 
     return 0; 

    for(int i=0;i<size;i++){ 
     map[A[i]] = i; 
    } 

    for(int i=0;i<size;i++){ 
     comp = K-A[i]; 
     unordered_map<long,long>::const_iterator index = map.find(comp); //error here 
     if(index == map.end()) 
      continue; 
     else{ 
      count++; 
     } 
    } 
    cout << "final count: " << count << endl; 
    return count;  
} 

我得到无效的操作数错误,我无法弄清楚我在做什么错。我试过切换迭代器,但它也可能是我的编译器。我使用这个编译:

铛++ -stdlib =的libC++ -std = GNU ++ 11 workingpairs.cpp

我的错误:预期 ';'声明结束 unordered_map :: const_iterator index = map.find(comp);

间接寻址需要指针操作数('int'无效) __table _.__ insert_unique(* __ first);

在函数模板专业化的实例化 '的std :: __ 1个:: unordered_map,性病:: __ 1 :: equal_to, 的std :: __ 1 ::分配器>> ::插入',这里要求

任何有识之士/帮助将不胜感激!

编辑:

我已经回到固定的错误。

+2

这是使用'汽车指数= map.find(COMP)的好地方;' – Blastfurnace

+0

@Blastfurnace代替const_interator的?或者除了它? – jshah

+0

我只会使用['auto'](http://en.cppreference.com/w/cpp/language/auto)关键字。编译器已经知道表达式'map.find(comp)'的类型,因此它会将'index'声明为该类型。这些繁琐的迭代器声明没有更多的错别字。 – Blastfurnace

回答

2

您在下面的语句错过::

unordered_map<long,long>const_iterator 

应该是:

unordered_map<long,long>::const_iterator 
+0

哇......谢谢! 我还有另一个错误:在函数模板专业化的实例化“的std :: __ 1 :: unordered_map <很长很长,性病:: __ 1 ::哈希,性病:: __ 1 :: equal_to , 的std :: __ 1 :: allocator >> insert ' map.insert(A [i],i);. 你知道那是什么吗? – jshah

+1

这是因为'map.insert(A [i],i);',插入可以采取配对,而不是键/值直接 – billz