2013-12-26 4 views
0

Я готовлю интервью для кодирования, поэтому я пишу код C++ на веб-сайте, на котором есть приятная сумка для образцов. При попытке скомпилировать мой код на веб-сайте (не совсем уверен, какая версия компилятора работает под капотом), я получаю очень своеобразную ошибку unordered_map. Я никогда не сталкивался с этой проблемой раньше, я провел некоторое исследование и выяснил, что ошибка произошла из-за того, как я инициализировал свой unordered_map. При инициализации моего unordered_map я использую строку C++ как мой ключ и значение, по какой-то причине компилятору это не нравится. Компилятор продолжает говорить, что нет хэш-функции для «basic_string», но я не использую basic_string, я использую C++ строкавопросов с C++ unordered_map

#include <cstdlib> 
#include <stdio.h> 
#include <iostream> 
#include <string> 
#include <vector> 
#include <unordered_map> 
#include <algorithm> 

using namespace std; 

void typeahead(const vector<string> &usernames, const vector<string> &queries) { 

//error occurs right here at this initialization 
//of HistoryHash 
unordered_map<string, string> HistoryHash; 
unordered_map<string, string>::iterator it; 
string cur_query, cur_usrnm; 
locale loc; 
//------------------------------------ 
//rest of code irrelevant 

Вот полный/полная ошибка:

In file included from /usr/include/c++/4.7/unordered_map:45:0, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable.h: In instantiation of 'void std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::insert(_InputIterator, _InputIterator) [with _InputIterator = std::basic_string<char>; _Key = std::basic_string<char>; _Value = std::pair<const std::basic_string<char>, std::basic_string<char> >; _Allocator = std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _ExtractKey = std::_Select1st<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _Equal = std::equal_to<std::basic_string<char> >; _H1 = std::hash<std::basic_string<char> >; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; bool 
__cache_hash_code = true; bool __constant_iterators = false; bool __unique_keys = true]': 
user_file.cpp:56:52: required from here 
/usr/include/c++/4.7/bits/hashtable.h:1410:61: error: no matching function for call to '__distance_fw(std::basic_string<char>&, std::basic_string<char>&)' 
/usr/include/c++/4.7/bits/hashtable.h:1410:61: note: candidates are: 
In file included from /usr/include/c++/4.7/bits/hashtable.h:36:0, 
       from /usr/include/c++/4.7/unordered_map:45, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable_policy.h:44:5: note: template<class _Iterator> typename std::iterator_traits::difference_type std::__detail::__distance_fw(_Iterator, _Iterator, std::input_iterator_tag) 
/usr/include/c++/4.7/bits/hashtable_policy.h:44:5: note: 
template argument deduction/substitution failed: 
In file included from /usr/include/c++/4.7/unordered_map:45:0, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable.h:1410:61: note: candidate expects 3 arguments, 2 provided 
In file included from /usr/include/c++/4.7/bits/hashtable.h:36:0, 
       from /usr/include/c++/4.7/unordered_map:45, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable_policy.h:50:5: note: template<class _Iterator> typename std::iterator_traits::difference_type std::__detail::__distance_fw(_Iterator, _Iterator, std::forward_iterator_tag) 
/usr/include/c++/4.7/bits/hashtable_policy.h:50:5: note: template argument deduction/substitution failed: 
In file included from /usr/include/c++/4.7/unordered_map:45:0, 
from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable.h:1410:61: note: candidate expects 3 arguments, 2 provided 
In file included from /usr/include/c++/4.7/bits/hashtable.h:36:0, 
       from /usr/include/c++/4.7/unordered_map:45, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable_policy.h:56:5: note: template<class _Iterator> typename std::iterator_traits::difference_type std::__detail::__distance_fw(_Iterator, _Iterator) 
/usr/include/c++/4.7/bits/hashtable_policy.h:56:5: note: template argument deduction/substitution failed: 
/usr/include/c++/4.7/bits/hashtable_policy.h: In substitution of 'template<class _Iterator> typename std::iterator_traits::difference_type std::__detail::__distance_fw(_Iterator, _Iterator) [with _Iterator = std::basic_string<char>]': 
/usr/include/c++/4.7/bits/hashtable.h:1410:61: required from 'void std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::insert(_InputIterator, _InputIterator) [with _InputIterator = std::basic_string<char>; _Key = std::basic_string<char>; _Value = std::pair<const std::basic_string<char>, std::basic_string<char> >; _Allocator = std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _ExtractKey = std::_Select1st<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _Equal = std::equal_to<std::basic_string<char> >; _H1 = std::hash<std::basic_string<char> >; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; bool __cache_hash_code = true; bool __constant_iterators = false; bool __unique_keys = true]' 
user_file.cpp:56:52: required from here 
/usr/include/c++/4.7/bits/hashtable_policy.h:56:5: error: no type named 'difference_type' in 'struct std::iterator_traits<std::basic_string<char> >' 
In file included from /usr/include/c++/4.7/unordered_map:45:0, 
       from user_file.cpp:6: 
/usr/include/c++/4.7/bits/hashtable.h: In instantiation of 'void std::_Hashtable<_Key, _Value, _Allocator, _ExtractKey, _Equal, _H1, _H2, _Hash, _RehashPolicy, __cache_hash_code, __constant_iterators, __unique_keys>::insert(_InputIterator, _InputIterator) [with _InputIterator = std::basic_string<char>; _Key = std::basic_string<char>; _Value = std::pair<const std::basic_string<char>, std::basic_string<char> >; _Allocator = std::allocator<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _ExtractKey = std::_Select1st<std::pair<const std::basic_string<char>, std::basic_string<char> > >; _Equal = std::equal_to<std::basic_string<char> >; _H1 = std::hash<std::basic_string<char> >; _H2 = std::__detail::_Mod_range_hashing; _Hash = std::__detail::_Default_ranged_hash; _RehashPolicy = std::__detail::_Prime_rehash_policy; bool __cache_hash_code = true; bool __constant_iterators = false; bool __unique_keys = true]': 
user_file.cpp:56:52: required from here 
/usr/include/c++/4.7/bits/hashtable.h:1418:2: error: no match for 'operator++' in '++__first' 
/usr/include/c++/4.7/bits/hashtable.h:1419:4: error: no match for 'operator*' in '*__first'" 
+2

Этот фрагмент ошибки почти бесполезен. Это все для одной информации об инстанцировании. Пожалуйста, покажите всю ошибку или, по крайней мере, фактическое сообщение об ошибке. – chris

+0

Вы должны попытаться уменьшить это до минимального образца кода, который воспроизводит проблему. Большая часть вашего кода кажется неактуальной. – juanchopanza

+0

Я сказал, что ошибка возникает при инициализации unordered_map, но я могу ее отредактировать и уменьшить. – AyBayBay

ответ

1

Это линия выглядит неправильно:

HistoryHash.insert(cur_query, local_min); 

Там нет перегрузки std::unordered_map<std::string, std::string>::insert который принимает две строки. Предположительно вы хотите

HistoryHash.insert(std::make_pair(cur_query, local_min)); 
+0

Да, я заметил, что эта строка не является причиной моей основной ошибки. Большая неприятная ошибка происходит там, где я инициализирую unordered_map – AyBayBay

+0

@AyBayBay Вы пытались удалить эту строку? Он компилируется для меня, поэтому, возможно, ваша стандартная библиотека не полностью соответствует требованиям. – juanchopanza

+0

это, казалось, сделало трюк, спасибо за помощь. Я не могу поверить, что эта строка может создать такие неприятные ошибки C++ действительно отстой! – AyBayBay

Смежные вопросы