the question I have is not about using a case-insensitive std::unordered_set, but rather how does it work?
#include "stdafx.h"
#include <string>
#include <iostream>
#include <unordered_set>
#include "boost/algorithm/string.hpp"
struct case_insensitive_comparer
{
bool operator () (const std::string& x, const std::string& y) const
{
return boost::iequals(x, y);
}
};
using case_insensitive_set = std::unordered_set<std::string, std::hash<std::string>, case_insensitive_comparer>;
std::vector<std::string> permute_case(const std::string& s)
{
std::vector<std::string> strs;
// Iterate through all bitmasks, 1 for uppercase, 0 for lowercase
int msb = 1 << (s.length() - 1);
int upper = 1 << s.length();
std::locale loc;
for (int i = 0; i < upper; i++)
{
int bit = msb;
std::string current = "";
for (size_t j = 0; j < s.length(); j++, bit >>= 1)
current += (bit & i) ? std::toupper(s[j], loc) : std::tolower(s[j], loc);
strs.push_back(current);
}
return strs;
}
int main()
{
std::vector<std::string> strs = permute_case("awesome");
case_insensitive_set set(strs.begin(), strs.end());
// Check the hash
for (auto& s : strs)
std::cout << s << " :" << std::hash<std::string>()(s) << "\n";
// Check the element
for (auto& s : set)
std::cout << s << "\n";
return 0;
}
So I use a string case-insensitive comparer for std::unordered_set
and the std::hash<std::string>
as the hash function. My basic understanding of hash set(I assume that unordered_set is like a hash set) is that it calculates the key's hash and puts it into the set if it doesn't exist yet. And the comparer Pred is for when the set is trying to insert a key and there is a hash collision, it has to decide if the keys are the same or different.
Based on the code, it works regardless, so some of my assumptions are not correct. It would be helpful if someone tell me which of my assumptions are wrong.
Thank you.
Edit: My expectation for this case insensitive unordered_set
is that there should only be 1 key inserted and it was the case that I observed, i.e only AWESOME is showed. So for my case I thought it worked but by the answer from kennytm really, I was just lucky getting all keys to be in the same bucket. I indeed use MSVC to compile the code.