c++ - 将 multimap<Key,Value> 转换为 vector <vector<Value>>

标签 c++ c++11 stl c++14

我需要转换std::unordered_multimap<Key,T>std::vector<std::vector<T>> 。我需要这样做,因为我的程序需要对所有数据进行排序,而 map 无法排序。一个例子:

// Map:
{ "A", 1 },
{ "A", 3 },
{ "A", 2 },
{ "B", 5 }, 
{ "B", 2 },

// Map converted to vector<vector<Value>>:
{ 1, 3, 2 }, 
{ 5, 2 }

现在我有了这段可以运行的代码。但我想知道这是否是最好的方法。

#include <unordered_map>
#include <iostream>
#include <string>
#include <vector>    

int main()
{
    typedef std::string Key_t;
    typedef int Value_t;
    typedef std::unordered_multimap<Key_t, Value_t> Map_t;

    const Map_t map = {
        { "A", 1 }, 
        { "A", 3 }, 
        { "A", 2 },
        { "B", 5 }, 
        { "B", 2 },
    };

    std::vector< std::vector< Value_t > > output;

    for ( Map_t::const_iterator it = map.cbegin(); it != map.cend(); )
    {
        std::vector< Value_t > temp;
        const Map_t::const_iterator end = map.upper_bound( it->first );
        for ( ; it != end; ++it )
            temp.push_back( it->second );

        output.push_back( temp );
    }

    // Print the result
    for ( const std::vector< Value_t >& values : output )
    {
        for ( const Value_t& value : values )
            std::cout << value << " ";

        std::cout << std::endl;
    }
}

输出:

1 3 2
5 2

所以,现在我想知道是否有更快/更好的方法。

最佳答案

这是我的尝试。

证据在这里:http://goo.gl/JVpHw9

#include <unordered_map>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
    typedef std::string Key_t;
    typedef int Value_t;
    typedef std::unordered_multimap<Key_t, Value_t> Map_t;

    const Map_t map = {
        { "A", 1 }, 
        { "A", 3 }, 
        { "A", 2 },
        { "B", 5 }, 
        { "B", 2 },
    };

    std::vector< std::vector< Value_t > > output;

    for (auto it = map.begin(); it != map.end(); )
    {
        auto er = map.equal_range(it->first);
        auto tmp = std::vector< Value_t >{};
        for( ; it != er.second ; ++it) {
            tmp.push_back(it->second);
        };
        output.push_back(std::move(tmp));
    }
    // Print the result
    for ( const std::vector< Value_t >& values : output )
    {
        for ( const Value_t& value : values )
            std::cout << value << " ";

        std::cout << std::endl;
    }
}

关于c++ - 将 multimap<Key,Value> 转换为 vector <vector<Value>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29594096/

相关文章:

c++ - C++ 标准要求使用 allocator::rebind 吗?

iphone - #include<vector> 没有这样的文件或目录

c++ - 为什么编译器会在这里提示函数歧义?

c++ - 自定义智能指针代码问题 - 智能指针不能在堆上结束吗?

c++ - 矩阵乘法问题

使用 OpenSSL 的 libcurl 的 Android-21 静态构建

c++ - 在 std::function 中存储函数指针

c++ - 赋值运算符 C++

c++ - 如何在通过 .def 文件导出函数时使用 dllImport 导入函数?

c++ - 正确使用 std::enable_if 或如何替换它