Critiques (even pedantic ones) are welcome.
bool unique_chars(std::string &s) {
if (s.length()>256) return false;
std::bitset<256> bs;
for (auto &c:s) {
if (bs.test(c)) return false;
bs.set(c);
}
return true;
}
That's pretty good. It's short. The early returns communicate intent well, and since the function is short, they don't get lost. Formatting is good, and the variable names, although very short, are common abbreveviations that work well here. I'd consider making the argument I've been out of C++ a long time, so I might be missing something here, but I'd consider |
||||
|
One theoretical place that this code might fail is when the string contains multibyte characters. For example UTF-8 encoding is being used and string passed to the function is "€Abبώиב¥£€¢₡₢₣₤₥₦§₧₨₩₪₫₭₮漢Ä©óíßä" although no character is being repeated, the function will return true. But handling this case is not straight forward at all, as standard library doesn't provide any way to iterate over actual characters in a string. |
|||
|
@Wayne Conrad has made some good points. I just have a few additional ones:
|
||||
|
There's no 'functional specification' included with your question, there is just the code. You should include a functional specification, a.k.a. "the problem" to be solved, or "the requirements". Without one, we can see what the code does, but cannot assess whether what it does matches what it is required . If the (missing) functional specification said, "string", then perhaps it doesn't mean only If so then your unique_chars should be a template function (in the same way that If you were working with very wide multi-byte characters (e.g. |
|||
|
std::basic_string<char>
andchar
is almost always 8 bits). – Corbin yesterday