【发布时间】:2016-11-16 21:28:16
【问题描述】:
我是 C++ 新手,可能在这里遗漏了一些非常基本的东西,但我正在尝试创建一个向量向量
#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;
}
我期待这样的输出
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
当我尝试在 main() 中打印向量的向量时,我得到所有向量的大小为 1。
好吧,当我打印地图中矢量的大小时,我觉得那里的大小还可以。我在这里错过了什么?
更新 -
通过以下更改修复它
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);
}
我仍然想知道是否有办法最终避免循环遍历地图并实现我最初打算做的事情?
【问题讨论】:
-
请注意
for(string s : strs)会复制strs中的每个字符串。 -
"...如果有办法避免最终循环遍历地图" - 我不想仅仅因为在那个时候很容易出错(非常错误)进入
vector< vector<string> & >领域。即使对于我自己的用途,我也会尽量避免传递引用类型的容器,因为如果您同时生成值只是为了将它们交给“外部”范围,那么它是内存管理不良的根源。您也可以使用指针,这很危险。