I am new to C++ and might be missing something very basic here but I am trying to create a vector of vectors
#include <iostream>
#include <stack>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs)
{
vector<vector<string>> result;
map<string,vector<string>> myMap;
if(strs.size() == 0)
{
return result;
}
for(string s : strs)
{
string temp = s;
sort(temp.begin(),temp.end());
auto it = myMap.find(temp);
if(it != myMap.end())
{
it->second.push_back(s);
}
else
{
vector<string> newVector;
newVector.push_back(s);
myMap.insert(pair<string,vector<string>>(temp,newVector));
result.push_back(newVector);
}
}
cout<< myMap["abt"].size() <<endl;
return result;
}
};
int main(int argc, const char * argv[])
{
Solution mySolution;
vector<string> myStrings {"eat", "tea", "tan", "ate", "nat", "bat"};
auto result = mySolution.groupAnagrams(myStrings);
for(vector<string> v: result)
{
//cout << v.size() << endl;
for(string s: v)
{
cout << s << " ";
}
cout << endl;
}
return 0;
}
I am expecting an output which looks like this
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
When I try to print the vector of vectors in main() I get all the size of the vectors as 1.
Well when I print the sizes of the vectors in the map, the sizes look okay to me there. What am I missing here?
UPDATE -
Fixed it with below change
for(string s : strs)
{
string temp = s;
sort(temp.begin(),temp.end());
auto it = myMap.find(temp);
if(it != myMap.end())
{
it->second.push_back(s);
}
else
{
vector<string> newVector;
newVector.push_back(s);
myMap.insert(pair<string,vector<string>>(temp,newVector));
}
}
for(auto it: myMap)
{
result.push_back(it.second);
}
I would still be interested to know if there is a way to avoid looping through the map in the end and achieve something which I initially intended to do?