fork(1) download
  1. #include <iostream>
  2.  
  3. #include <map>
  4. #include <string>
  5.  
  6. using Map = std::map<std::string, int>; // we don't care about the value here
  7.  
  8. Map const m = { { "/a/b/c", 0 },
  9. { "/a/b/d", 0 },
  10. { "/a/b/c/d", 0 },
  11. { "/e/f/g", 0 },
  12. { "/a/x/v", 0 },
  13. { "/e", 0 },
  14. { "/a/b/c/d/e", 0 } };
  15.  
  16. int main() {
  17. // Note: string comparison orders the string lexicographically
  18. // with shorter strings coming first
  19. auto current = m.begin();
  20. for (auto it = next(current), end = m.end(); it != end; ++it ) {
  21. // Note: if current is not a prefix of "it", then it cannot be a prefix
  22. // of any key that comes after "it", however of course "it" could
  23. // be such a prefix.
  24.  
  25. // current is not a prefix of "it" if "it" is shorter
  26. if (it->first.size() <= current->first.size()) { current = it; continue; }
  27.  
  28. // current is not a prefix of "it"
  29. if (it->first.substr(0, current->first.size()) != current->first) { current = it; continue; }
  30.  
  31. // current is a prefix
  32. std::cout << "'" << current->first << "' is a prefix of '" << it->first << "'\n";
  33. }
  34. return 0;
  35. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
'/a/b/c' is a prefix of '/a/b/c/d'
'/a/b/c' is a prefix of '/a/b/c/d/e'
'/e' is a prefix of '/e/f/g'