在C++和push_back()中使用向量向量

kim*_*imi 2 c++ vector

我是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;
}
Run Code Online (Sandbox Code Playgroud)

我期待一个看起来像这样的输出

[
  ["ate", "eat","tea"],
  ["nat","tan"],
  ["bat"]
]
Run Code Online (Sandbox Code Playgroud)

当我尝试在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);
}
Run Code Online (Sandbox Code Playgroud)

我仍然有兴趣知道是否有办法避免在最后通过地图循环并实现我最初打算做的事情?

Xer*_*rcy 5

这是这部分:

{
    vector<string> newVector;
    newVector.push_back(s);
    myMap.insert(pair<string,vector<string>>(temp,newVector));
    result.push_back(newVector);
}
Run Code Online (Sandbox Code Playgroud)

每次result都给出一个具有一个元素的新向量.更改地图的矢量工作而不是矢量矢量的原因是因为vector::push_back每次都创建一个副本.


要解决这个问题,有两种方法.

  1. 您可以尝试在地图的同时更新结果,并获取向量以存储对地图副本的一些引用.
  2. 由于您不使用result处理步骤,仅用于结果,因此您可以在完成地图后编译向量.

我更喜欢方法#2,因为你永远不会返回地图本身.此外,还有一种从一种容器类型转换到另一种容器类型的艺术,例如,这个问题提供了一些关于所涉及的内容的想法.