A have a vector of strings in c++:
vector<string> myVect = {"A", "A", "A", "B", "B", "A", "C", "C", "foo", "A", "foo"};
How can I convert this to a vector of integers, so that each integer uniquely corresponds to a string in myVect?
i.e. I would like a vector
out = {0, 0, 0, 1, 1, 0, 2, 2, 3, 0, 3}
In addition, I would like a vector of the unique strings, each position corresponding to the number in out:
uniqueStrings = {"A", "B", "C", "foo"}
So far I have the following:
vector<string> uniqueStrings; // stores list of all unique strings
vector<int> out(myVect.size());
for (int i = 0; i < myVect.size(); ++i)
{
// seeing if this string has been encountered before
bool assigned = false;
for (int j = 0; j < uniqueStrings.size(); ++j)
if (!myVect.at(i).compare( uniqueStrings.at(j) ))
{
out.at(i) = j;
assigned = true;
break;
}
// if not, add new example to uniqueStrings
if (!assigned)
{
uniqueStrings.push_back(myVect.at(i));
out.at(i) = uniqueStrings.size();
}
}
This works, but surely there must be a better way?
Here’s a more or less complete example of how you might use a
std::map<>to maintain a mapping of unique strings to an integer ID: