Given two strings, determine if one is a permutation of the other After comparing my newbie attempt with other people's answers, I have a couple questions:


I've made s1_set the size of s1. I've seen other people assume that the strings are ASCII-256 and use s1_set(256) but to me this doesn't make sense. Won't s1_set have at most s1.size() bytes (and fewer if s1 has duplicate characters)?
I've also seen explicit casting before accessing s1_set: int val = static_cast&lt;int&gt;(x);. Is this necessary? Is it bad form to use implicit casting?
Would it be preferred to use the regular for statement, or does the range-for work just as well?




#include &lt;iostream&gt;
#include &lt;vector&gt;

using namespace std;

bool is_permutation(const string&amp; s1, const string&amp; s2) {
  if (s1.size() != s2.size()) {
    return false;
  }

  vector&lt;int&gt; s1_set(s1.size());
  for (const auto&amp; x : s1) { 
    ++s1_set[x];
  }

  for (const auto&amp; x : s2) {
    if (--s1_set[x] &lt; 0) {
      return false;
    }
  }

  return true;
}

int main(int argc, char* argv[]) {
  cout &lt;&lt; is_permutation("AABC", "BCBA") &lt;&lt; endl; // false
  cout &lt;&lt; is_permutation("BC", "CBA") &lt;&lt; endl; // false, different sizes
  cout &lt;&lt; is_permutation("ABC", "CBA") &lt;&lt; endl; // true
  cout &lt;&lt; is_permutation("AABC", "ACBA") &lt;&lt; endl; // true
}
This code is broken.

// This creates an array with size elements all set to zero.
// But your string (in the examples) are not more than 4 long.
// So the largest vector is 4 elements long.
vector&lt;int&gt; s1_set(s1.size());

// Here x is char.
for (const auto&amp; x : s1) { 
// It is undefined if char is signed or unsigned.
// so the range of values for x is
//       0 -&gt; 255
// or -127 -&gt; 128
//
// Either way the range is well beyond the size of
// the array defined above.