Как проверить наличие ключа в Hashmap
Иначе, вы можете просто проверить, что такой ключ существует, если получили значение null :
Foo value = map.get(key); if (value != null) < . >else < // Ключ может быть. if (map.containsKey(key)) < // Ключ присутствует, но значение null >else < // Определенно нет ключа >>
Отслеживать
ответ дан 19 апр 2016 в 14:48
80.9k 9 9 золотых знаков 78 78 серебряных знаков 134 134 бронзовых знака
-
Важное на Мете
Похожие
Подписаться на ленту
Лента вопроса
Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.
Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.11.21.1314
Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.
Как проверить есть ли в map ключ
Здравствуйте, Аноним, Вы писали:
А>Как проверить наличие ключа в мапе?
myMapType::iterator I = myMap.find( myKey ); if ( I != myMap.end()) I->second = myValue;
Re: std::map наличие ключа
| От: | Аноним |
| Дата: | 22.03.09 17:21 |
| Оценка: |
Нужно сделать вроде этого:
if(myMap.find(myKey)== myMap.end())
if(myMap.insert(MyMapType::value_type(myKey, myValue).second) < //inserted > else < //already existed >
Re[2]: std::map наличие ключа
| От: | A.Lokotkov | http://www.linkedin.com/pub/alexander-lokotkov/a/701/625 |
| Дата: | 22.03.09 18:56 | |
| Оценка: |
В смысле, наоборот:
if ( myMap.find( myKey ) == myMap.end() ) myMap[myKey] = myValue;
bloß it hudla
Re[3]: std::map наличие ключа
| От: | Were |
| Дата: | 22.03.09 19:52 |
| Оценка: |
Здравствуйте, A.Lokotkov, Вы писали:
AL>В смысле, наоборот:
AL>
AL>if ( myMap.find( myKey ) == myMap.end() ) AL> myMap[myKey] = myValue; AL>
Re[3]: std::map наличие ключа
| От: | Vain | google.ru |
| Дата: | 22.03.09 22:12 | |
| Оценка: |
Здравствуйте, A.Lokotkov, Вы писали:
AL>В смысле, наоборот:
AL>
AL>if ( myMap.find( myKey ) == myMap.end() ) AL> myMap[myKey] = myValue; AL>
Так 2 раза будет искать.
[In theory there is no difference between theory and practice. In
practice there is.]
[Даю очевидные ответы на риторические вопросы]
Re[4]: std::map наличие ключа
| От: | _DAle_ |
| Дата: | 23.03.09 00:02 |
| Оценка: |
Здравствуйте, Vain, Вы писали:
V>Здравствуйте, A.Lokotkov, Вы писали:
AL>>В смысле, наоборот:
AL>>
AL>>if ( myMap.find( myKey ) == myMap.end() ) AL>> myMap[myKey] = myValue; AL>>
V>Так 2 раза будет искать.
Да, но зато это в отличие от предыдущей версии делает то, что просил автор топика.
Если нужно, чтобы поиск был только один раз то нужно сделать, как уже сказали раньше, вот так:
myMap.insert(make_pair(myKey, myValue));
Re[5]: std::map наличие ключа
| От: | Vain | google.ru |
| Дата: | 23.03.09 02:34 | |
| Оценка: |
Здравствуйте, _DAle_, Вы писали:
V>>Так 2 раза будет искать.
_DA>Да, но зато это в отличие от предыдущей версии делает то, что просил автор топика.
Что не так с предыдущей
Автор: Were
Дата: 22.03.09
[In theory there is no difference between theory and practice. In
practice there is.]
[Даю очевидные ответы на риторические вопросы]
Re[6]: std::map наличие ключа
| От: | A.Lokotkov | http://www.linkedin.com/pub/alexander-lokotkov/a/701/625 |
| Дата: | 23.03.09 03:31 | |
| Оценка: |
Здравствуйте, Vain, Вы писали:
V>Что не так с предыдущей
Автор: Were
Дата: 22.03.09
По условию топик-стартера вставляем, если ключа в мапе нет. В той версии
Автор: Were
Дата: 22.03.09
bloß it hudla
Re: std::map наличие ключа
| От: | Bell | |
| Дата: | 23.03.09 04:17 | |
| Оценка: | 5 (3) +2 | |
Здравствуйте, Аноним, Вы писали:
Если нужно просто проверить наличие ключа — то можно так:
if(myMap.count(myKey))
главное преимущество — меньше писанины
Любите книгу — источник знаний (с) М.Горький
Re[2]: std::map наличие ключа
| От: | IROV.. |
| Дата: | 23.03.09 11:20 |
| Оценка: |
Здравствуйте, Bell, Вы писали:
B>Здравствуйте, Аноним, Вы писали:
B>Если нужно просто проверить наличие ключа — то можно так:
B>
B>if(myMap.count(myKey)) B>
B>главное преимущество — меньше писанины
главный недостаток, в N раз медленее
я не волшебник, я только учусь!
Re: std::map наличие ключа
| От: | IROV.. | |
| Дата: | 23.03.09 11:31 | |
| Оценка: | 2 (1) | |
Здравствуйте, Аноним, Вы писали:
А>Как проверить наличие ключа в мапе?
А>Нужно сделать вроде этого:
А>
А>if(!myMap.ExistKey(myKey)) А> < А>myMap[myKey] = myValue; А>> А>
это уже проверит, и вставит.
если нужно «если нету, то вставить».
myMap.insert( std::make_pair( myKey, myValue ) );
если нужно при этом еще и узнать вставило оно или нет то пишем так
bool inserted = myMap.insert( std::make_pair( myKey, myValue ) ).second;
я не волшебник, я только учусь!
Re[2]: std::map наличие ключа
| От: | A.Lokotkov | http://www.linkedin.com/pub/alexander-lokotkov/a/701/625 |
| Дата: | 23.03.09 11:44 | |
| Оценка: |
Здравствуйте, IROV. Вы писали:
IRO>ну вопервых
IRO>myMap[myKey] = myValue;
IRO>это уже проверит, и вставит.
если по заданному ключу до вставки лежит очень нужный объект, то он окажется в космосе. хотя, вероятно, топик-стартер этого в виду не имел.
bloß it hudla
Re[3]: std::map наличие ключа
| От: | IROV.. |
| Дата: | 23.03.09 12:01 |
| Оценка: |
Здравствуйте, A.Lokotkov, Вы писали:
AL>Здравствуйте, IROV. Вы писали:
IRO>>ну вопервых
IRO>>myMap[myKey] = myValue;
IRO>>это уже проверит, и вставит.
AL>если по заданному ключу до вставки лежит очень нужный объект, то он окажется в космосе. хотя, вероятно, топик-стартер этого в виду не имел.
да именно, это метод update map
я не волшебник, я только учусь!
Re[3]: std::map наличие ключа
| От: | Bell |
| Дата: | 23.03.09 12:54 |
| Оценка: |
Здравствуйте, IROV. Вы писали:
B>>Если нужно просто проверить наличие ключа — то можно так:
B>>
B>>if(myMap.count(myKey)) B>>
B>>главное преимущество — меньше писанины
IRO>главный недостаток, в N раз медленее
Может быть будут аргументы?
ЗЫ
На всякий случай: В табличке 69 в требованиях к сложности стоит логарифм.
Любите книгу — источник знаний (с) М.Горький
Re[4]: std::map наличие ключа
| От: | IROV.. |
| Дата: | 23.03.09 13:30 |
| Оценка: |
Здравствуйте, Bell, Вы писали:
B>Здравствуйте, IROV. Вы писали:
B>>>Если нужно просто проверить наличие ключа — то можно так:
B>>>
B>>>if(myMap.count(myKey)) B>>>
B>>>главное преимущество — меньше писанины
IRO>>главный недостаток, в N раз медленее
B>Может быть будут аргументы?
Гавно, вопрос.
size_type count(const key_type& _Keyval) const < // count all elements that match _Keyval _Paircc _Ans = equal_range(_Keyval); size_type _Num = 0; _Distance(_Ans.first, _Ans.second, _Num); return (_Num); >
что мы тут видем, equal_range -> два find.
Distance!! может для когото секрет, что итерация у std::map это совсем не константная операция.
я не волшебник, я только учусь!
Re[5]: std::map наличие ключа
| От: | _DAle_ |
| Дата: | 23.03.09 13:37 |
| Оценка: |
Здравствуйте, IROV. Вы писали:
IRO>Гавно, вопрос.
IRO>
IRO> size_type count(const key_type& _Keyval) const IRO> < // count all elements that match _Keyval IRO> _Paircc _Ans = equal_range(_Keyval); IRO> size_type _Num = 0; IRO> _Distance(_Ans.first, _Ans.second, _Num); IRO> return (_Num); IRO> > IRO>
IRO>что мы тут видем, equal_range -> два find.
IRO>Distance!! может для когото секрет, что итерация у std::map это совсем не константная операция.
Осталось только сказать, что в мэпе всегда в интервале будет максимум один элемент, и никто не запрещал автора реализовать count для map более эффективно.
Re[6]: std::map наличие ключа
| От: | _DAle_ |
| Дата: | 23.03.09 13:41 |
| Оценка: |
Здравствуйте, _DAle_, Вы писали:
_DA>Здравствуйте, IROV. Вы писали:
IRO>>Гавно, вопрос.
IRO>>
IRO>> size_type count(const key_type& _Keyval) const IRO>> < // count all elements that match _Keyval IRO>> _Paircc _Ans = equal_range(_Keyval); IRO>> size_type _Num = 0; IRO>> _Distance(_Ans.first, _Ans.second, _Num); IRO>> return (_Num); IRO>> > IRO>>
IRO>>что мы тут видем, equal_range -> два find.
IRO>>Distance!! может для когото секрет, что итерация у std::map это совсем не константная операция.
_DA>Осталось только сказать, что в мэпе всегда в интервале будет максимум один элемент, и никто не запрещал автора реализовать count для map более эффективно.
В stlport это выглядит так:
size_type count(const _KT& __x) const < return _M_t.find(__x) == _M_t.end() ? 0 : 1; >
Ленивые.. А можно ведь сделать лучше.
Re[7]: std::map наличие ключа
| От: | IROV.. |
| Дата: | 23.03.09 13:47 |
| Оценка: |
Здравствуйте, _DAle_, Вы писали:
_DA>Здравствуйте, _DAle_, Вы писали:
_DA>>Здравствуйте, IROV. Вы писали:
IRO>>>Гавно, вопрос.
IRO>>>
IRO>>> size_type count(const key_type& _Keyval) const IRO>>> < // count all elements that match _Keyval IRO>>> _Paircc _Ans = equal_range(_Keyval); IRO>>> size_type _Num = 0; IRO>>> _Distance(_Ans.first, _Ans.second, _Num); IRO>>> return (_Num); IRO>>> > IRO>>>
IRO>>>что мы тут видем, equal_range -> два find.
IRO>>>Distance!! может для когото секрет, что итерация у std::map это совсем не константная операция.
_DA>>Осталось только сказать, что в мэпе всегда в интервале будет максимум один элемент, и никто не запрещал автора реализовать count для map более эффективно.
Одна итерация, так одна от begin -> end ^^
начнем с того что сама функция count вообще както глупо выглядит
_DA>В stlport это выглядит так:
_DA>
_DA>size_type count(const _KT& __x) const < return _M_t.find(__x) == _M_t.end() ? 0 : 1; > _DA>
_DA>Ленивые.. А можно ведь сделать лучше.
наверное в stl от мелких, идет впервую очередь обощеность кода (минимум), и поэтому база для map и для multimap идет одна, а в stlport просто выжимают соки.
в любом случаее лучше count не пользоватся, как по мне в map это рудимент от multimap
я не волшебник, я только учусь!
Re[8]: std::map наличие ключа
| От: | _DAle_ |
| Дата: | 23.03.09 13:55 |
| Оценка: |
Здравствуйте, IROV. Вы писали:
IRO>Одна итерация, так одна от begin -> end ^^
Просто в N раз никакого замедления не будет, максимум в 2 из-за ненужного вызова equal_range.
IRO>начнем с того что сама функция count вообще както глупо выглядит
Согласен, но она делает именно то, что часто надо, хоть и в кривой форме.
_DA>>В stlport это выглядит так:
_DA>>
_DA>>size_type count(const _KT& __x) const < return _M_t.find(__x) == _M_t.end() ? 0 : 1; > _DA>>
_DA>>Ленивые.. А можно ведь сделать лучше.
IRO>наверное в stl от мелких, идет впервую очередь обощеность кода (минимум), и поэтому база для map и для multimap идет одна, а в stlport просто выжимают соки.
А кому нужна эта конкретная обобщенность кроме самих разработчиков stl? Мне от stl часто нужна скорость.
IRO>в любом случаее лучше count не пользоватся, как по мне в map это рудимент от multimap
Check if Key Exists in a Map in C++
- Use the std::map::find Function to Check if Key Exists in a C++ Map
- Use the std::map::count Function to Check if Key Exists in a C++ Map
- Use the std::map::contains Function to Check if Key Exists in a C++ Map
- Use the std::map::at Function With Exception Handling to Check if Key Exists in a C++ Map
- Use a for Loop to Check if Key Exists in a C++ Map
- Conclusion
In C++, maps are a fundamental data structure that stores elements in a key-value pair fashion. Often, it becomes crucial to determine whether a specific key exists within a map before attempting any operations involving it. This task is essential for avoiding potential errors or unexpected behavior in a program.
This article will introduce methods on how to check if a key exists in a map in C++. Each method offers its approach, catering to different scenarios and preferences.
Use the std::map::find Function to Check if Key Exists in a C++ Map
The std::map is a part of the Standard Template Library (STL) in C++. It is a container that stores elements in key-value pairs, where each key is unique. The elements are sorted by their keys, which allows for efficient lookup operations based on the key.
On the other hand, STL also provides an unsorted version of the same container named std::unordered_map . Both of these containers support the key searching methods that are described in this article.
To use std::map , you need to include the header file:
#include
You can declare a map using the following syntax:
std::mapKeyType, ValueType> myMap;
Here, KeyType is the type of the keys, and ValueType is the type of the values.
The find() function is a member function of the std::map class that allows you to search for a specific key within the map. It returns an iterator pointing to the element if the key is found or myMap.end() if the key is not present.
iterator find(const KeyType& key); const_iterator find(const KeyType& key) const;
- key : The the key you want to search for.
- iterator : The type of the iterator for a non- const map.
- const_iterator : The type of the iterator for a const map.
In the following example, we initialize the map of std::pair types and then take the key value from the user input passed to the find() function. The example program outputs the affirmative string to the cout stream.
#include #include using std::cin; using std::cout; using std::endl; using std::map; using std::string; int main() string key_to_find; std::mapstring, string> lang_map = < "j", "Julia", >, "p", "Python", >, "m", "MATLAB", >, "o", "Octave", >, "s", "Scala", >, "l", "Lua", >>; for (const auto& [key, value] : lang_map) cout <" : " > cout <"Enter the key to search for: "; cin >> key_to_find; if (lang_map.find(key_to_find) != lang_map.end()) cout <"Key Exists!" > else cout <"Key does not exist!" > return EXIT_SUCCESS; >
This code first includes necessary header files like and . Then, it sets up aliases for std::cout , std::cin , std::endl , std::map , and std::string for convenience.
Inside the main function, a string variable key_to_find is declared to hold the user’s input for the key they want to search. Next, a std::map called lang_map is created and initialized with key-value pairs representing programming languages and their respective keys.
The code then enters a loop that iterates through each element in lang_map using a range-based for loop. In each iteration, it prints out the key-value pairs using std::cout .
After displaying the available keys and their corresponding languages, the program prompts the user to enter a key they want to search for. This input is stored in the key_to_find variable.
Next, it uses lang_map.find(key_to_find) to search for the specified key in the map. If the find function does not return lang_map.end() (indicating that the key was found), it prints «Key Exists!» . Otherwise, it prints «Key does not exist!» .
j : Julia l : Lua m : MATLAB o : Octave p : Python s : Scala Enter the key to search for: l Key Exists!
Use the std::map::count Function to Check if Key Exists in a C++ Map
Alternatively, one can utilize the count built-in function of the std::map container to check if a given key exists in a map object. Note that the count function retrieves the number of elements that have the given key value.
size_type count(const KeyType& key) const;
- key : The key that you want to count in the map.
- size_type : This is an unsigned integral type representing the size or count of elements in the map. It is typically std::size_t .
Since map keys are unique, the return value will either be 1 (if the key is found) or 0 (if not found). Thus, we can use the count function call as an if condition to output the affirming string when the given key exists in a map object.
The following code prompts the user for a key, checks if it exists in the map using the count() function, and then provides feedback based on whether or not the key is found.
#include #include using std::cin; using std::cout; using std::endl; using std::map; using std::string; int main() string key_to_find; std::mapstring, string> lang_map = < "j", "Julia", >, "p", "Python", >, "m", "MATLAB", >, "o", "Octave", >, "s", "Scala", >, "l", "Lua", >>; cout <"Enter the key to search for: "; cin >> key_to_find; if (lang_map.count(key_to_find)) cout <"Key Exists!" > else cout <"Key does not exist!" > return EXIT_SUCCESS; >
This code begins by including necessary header files like for input/output operations and for using the std::map container. Then, it sets up aliases for std::cout , std::cin , std::endl , std::map , and std::string to simplify the code.
In the main function, a string variable key_to_find is declared to store the user’s input. Next, a std::map named lang_map is created and initialized with key-value pairs representing programming languages and their respective keys.
The program then prompts the user with the message «Enter the key to search for: » . The user’s input is stored in the variable key_to_find .
Afterwards, it uses lang_map.count(key_to_find) to check if the entered key exists in the map. If the count is greater than 0 (indicating that the key was found), it prints «Key Exists!» . Otherwise, it prints «Key does not exist!» .
Enter the key to search for: l Key Exists!
Use the std::map::contains Function to Check if Key Exists in a C++ Map
The contains() method was introduced in C++20 and is another built-in function that can be used to find if the key exists in a map. This function returns a Boolean value if the element with the given key exists in the object.
bool contains(const KeyType& key) const;
- key : The key that you want to check for in the map.
This function returns true if the map contains an element with the specified key and false otherwise.
The following code prompts the user for a key, checks if it exists in the map using the contains() method, and then provides feedback based on whether or not the key is found.
Please note that the program below assumes C++20 or later versions where the contains() method is available.
#include #include using std::cin; using std::cout; using std::endl; using std::map; using std::string; int main() string key_to_find; std::mapstring, string> lang_map = < "j", "Julia", >, "p", "Python", >, "m", "MATLAB", >, "o", "Octave", >, "s", "Scala", >, "l", "Lua", >>; cout <"Enter the key to search for: "; cin >> key_to_find; if (lang_map.contains(key_to_find)) cout <"Key Exists!" > else cout <"Key does not exist!" > return EXIT_SUCCESS; >
After including necessary libraries and setting up aliases for convenience, the main function begins. A string variable named key_to_find is declared to store the user’s input for the key they wish to search.
Next, a std::map called lang_map is created and initialized with key-value pairs representing programming languages and their respective keys. This map associates single-letter keys ( «j» for Julia , «p» for Python , and so on) with the corresponding language names.
The program then prompts the user with the message «Enter the key to search for: » , and awaits their input, which is stored in the key_to_find variable.
Subsequently, it employs the lang_map.contains(key_to_find) statement to check if the specified key exists in the map. If the condition evaluates to true , it prints «Key Exists!» , otherwise it prints «Key does not exist!» .
Enter the key to search for: l Key Exists!
Use the std::map::at Function With Exception Handling to Check if Key Exists in a C++ Map
The at() function is used to access the element at a specified position in the map. By using this function in combination with exception handling, we can determine if a key exists in the map.
mapped_type& at(const KeyType& key); const mapped_type& at(const KeyType& key) const;
- key : The key whose associated value you want to access.
- mapped_type : The type of the mapped values in the map.
- KeyType : The type of the keys in the map.
This function returns a reference to the value associated with the specified key. If the key does not exist in the map, it throws a std::out_of_range exception.
The following code demonstrates how to use exception handling to check if a key exists in a map. If the key is found, it prints the associated value; otherwise, it catches the exception and prints a message indicating that the key was not found. This approach ensures robustness in handling potential key lookup errors.
#include #include int main() std::mapint, std::string> myMap = 1, "One">, 2, "Two">, 3, "Three">>; // Check if the key exists try std::string value = myMap.at(2); std::cout <"Key found! Value is: " :: endl; > catch (const std::out_of_range& oor) std::cout <"Key not found." :: endl; > return 0; >
In this code, a std::map named myMap is declared and initialized with three key-value pairs. The code proceeds to perform a key lookup operation using the try-catch mechanism.
Within the try block, it attempts to access the value associated with the key 2 using the statement myMap.at(2) . If the key is present in the map, the associated value ( «Two» ) is assigned to the variable value , and it prints «Key found! Value is: Two» to the console.
However, if the key is not found in the map, a std::out_of_range exception is thrown. This is caught in the catch block, and it executes the code within. If this is the case, it prints «Key not found» to the console.
Key found! Value is: Two
Use a for Loop to Check if Key Exists in a C++ Map
One approach to check if a key exists in a map is by using a for loop to iterate through the map’s elements and comparing each key with the target key. You can use a for loop along with an if statement to check if a key exists in a map in C++.
In this example, the for loop iterates through the map and checks if the specified key exists. If found, key_exists is set to true , and the loop is exited. Finally, it prints a message indicating whether the key exists or not.
#include #include int main() std::mapint, std::string> myMap = 1, "One">, 2, "Two">, 3, "Three">>; int key_to_find = 2; bool key_exists = false; // Check if the key exists using a for loop for (const auto& pair : myMap) if (pair.first == key_to_find) key_exists = true; break; > > if (key_exists) std::cout <"Key exists!" :: endl; > else std::cout <"Key does not exist." :: endl; > return 0; >
This code demonstrates how to check if a specific key exists in a std::map without using the find() or at() functions. It begins by including the necessary header files, and . In the main function, a std::map called myMap is created, associating integer keys with corresponding string values.
The code then sets key_to_find to 2 and initializes a Boolean variable key_exists as false . Next, it employs a for loop to iterate through each pair in myMap .
For each pair, it checks if the first element (the key) matches the value of key_to_find . If a match is found, key_exists is set to true , and the loop is exited using the break statement.
Following the loop, it evaluates key_exists . If it is true , it prints «Key exists!» , otherwise, it prints «Key does not exist.» .
Key exists!
Using a for loop to check for key existence in a C++ map provides a straightforward and effective approach. However, it’s worth noting that this method may not be as efficient as using the find() function for large maps.
Conclusion
In summary, this article explored various methods to check if a key exists in a C++ map.
The std::map::find function provides a direct way to search for a key, returning an iterator to the element if found. The std::map::count function efficiently retrieves the number of elements with a given key, yielding either 1 (if found) or 0 (if not).
Introduced in C++20, the std::map::contains method offers a concise way to perform key existence checks. Exception handling with std::map::at provides a robust approach to determine if a key exists.
Additionally, a for loop with an if statement allows for manual key checking by iterating through the map.
These methods cater to different scenarios, empowering developers to effectively handle key existence checks in maps.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
Related Article — C++ Map
- Insert New Elements in an STL Map in C++
- Use the std::map::find Function in C++
- Use an STL Map Container in C++
- Use the STL Unordered Map Container in C++
- Sort Map by Value in C++
Определите, существует ли ключ на карте в C++
В этом посте будет обсуждаться, как определить, существует ли ключ в карте на C++.
1. Использование std::map::find
Стандартный способ использования std::map::find функция, которая ищет на карте ключ и возвращает ему итератор, или std::map::end если ключа нет в карте. В следующем примере кода показан вызов этой функции:
std :: map < std :: string , int >map = < std :: string key = "two" ; if ( map . find ( key ) != map . end ( ) ) < std :: cout << "Key found" << std :: endl ; std :: cout << "Key not found" << std :: endl ;
результат:
Key found
2. Использование std::map::count
Другой вариант — использовать std::map::count чтобы получить общее количество элементов на карте с определенным ключом. Если на карте присутствует ключ, счетчик будет ровно 1, поскольку все ключи в контейнере карты уникальны. Если ключ не найден, функция count возвращает ноль.
