I want to create std::unordered_map<char, std::size_t> , which for each added character will store the number under which it was added (starting from 0, the added characters are unique). I think to write

 std::unordered_map<char, std::size_t> map; for (auto character : characters) map[character]=map.size(); 

Would it be a UB ? Is there a better way?

  • map[character] = 0; map[character] = map.size() - 1 map[character] = 0; map[character] = map.size() - 1 - vegorov
  • one
    And why should it be UB? - vegorov
  • and characters is what? - AR Hovsepyan

1 answer 1

 void creat_map( std::unordered_map<char, std::size_t>& map, const std::string& characters ) { static size_t index{}; for (char ch : characters) map[ch] = index++; } 

not to call map.size() every time