Created
April 20, 2020 14:09
-
-
Save abdalmoez/657bcb46cf596742e71caf5c3f9fa65d to your computer and use it in GitHub Desktop.
Get the first empty key in map<int, TValue>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <map> | |
template<typename TValue> | |
int locateFirstAvailableSlot(std::map<int, TValue> my_map) | |
{ | |
typename std::map<int, TValue>::iterator it; | |
int expected_value=1; | |
for ( it = my_map.begin(); it != my_map.end(); it++ ) | |
{ | |
if(it->first == expected_value) | |
{ | |
expected_value++; | |
} | |
else | |
{ | |
return expected_value; | |
} | |
} | |
return expected_value; | |
} | |
int main() | |
{ | |
std::map<int, std::string> series; | |
series.insert ( std::pair<int,std::string>(100, "ok") ); | |
std::cout<<"Expectedvalue: 1, ActualValue: "<< locateFirstAvailableSlot(series)<<std::endl; | |
std::map<int, std::string> series2; | |
std::cout<<"Expectedvalue: 1, ActualValue: "<< locateFirstAvailableSlot(series2)<<std::endl; | |
std::map<int, std::string> series3; | |
series3.insert ( std::pair<int,std::string>(1, "First") ); | |
series3.insert ( std::pair<int,std::string>(2, "Second") ); | |
series3.insert ( std::pair<int,std::string>(4, "Forth") ); | |
std::cout<<"Expectedvalue: 3, ActualValue: "<< locateFirstAvailableSlot(series3)<<std::endl; | |
std::map<int, char> series4; | |
series4.insert ( std::pair<int,char>(1, 'a') ); | |
series4.insert ( std::pair<int,char>(2, 'b') ); | |
std::cout<<"Expectedvalue: 3, ActualValue: "<< locateFirstAvailableSlot(series4)<<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment