fork download
  1. #include <iostream>
  2. #include <regex>
  3. #include <string>
  4. #include <vector>
  5.  
  6. std::vector<std::pair<std::string, std::size_t>> Extract(const std::string& s)
  7. {
  8. std::vector<std::pair<std::string, std::size_t>> res;
  9. const std::regex reg{R"(([a-zA-Z]+)(\d*))"};
  10.  
  11. for (auto it = std::sregex_iterator(s.begin(), s.end(), reg); it != std::sregex_iterator(); ++it)
  12. {
  13. auto m = *it;
  14. res.push_back({m[1], m[2].length() == 0 ? 1 : std::stoi(m[2])});
  15. }
  16. return res;
  17. }
  18.  
  19. int main() {
  20. for (auto p : Extract("C6H12O6")) {
  21. std::cout << p.first << ": " << p.second << std::endl;
  22. }
  23. std::cout << std::endl;
  24. for (auto p : Extract("H2O")) {
  25. std::cout << p.first << ": " << p.second << std::endl;
  26. }
  27. }
Success #stdin #stdout 0s 4460KB
stdin
Standard input is empty
stdout
C: 6
H: 12
O: 6

H: 2
O: 1