【问题标题】:storing map<string, struct> into vector to sort将 map<string, struct> 存储到向量中进行排序
【发布时间】:2016-04-16 01:53:21
【问题描述】:

我正在尝试以下代码。我正在尝试按升序或降序大小以及从 z-a (三种不同的排序)对其进行排序。我不知道如何将它存储在向量中,更不用说对其进行排序了。感谢您的帮助!

  struct countSize {
        int count;
        uintmax_t size;

        void sortMap(map<string, countSize> &extCount)
    {
        // Copy 
        vector<string, countSize> v(extCount.begin(), extCount.end());

        // Sort the vector according to either file size or desc alphabetically


        //print

    }

int main()
{
map<string, countSize> mp;
 mp["hello"] = { 1, 200 };
 mp["Ace"] = { 5, 600 };
 mp["hi"] = { 3, 300 };
mp["br"] = { 2, 100 };

sortMap(mp);
}

【问题讨论】:

    标签: sorting dictionary vector struct


    【解决方案1】:

    如果您遍历地图,您会得到std::pair&lt;const X, Y&gt; 的流。由于const,这对于存储在向量中有点尴尬。一种解决方案是删除const

    using my_map = std::map<std::string, countSize>;
    // Mutable element type.
    using my_map_element = std::pair<typename my_map::key_type,
                                     typename my_map::mapped_type>;
    using my_element_list = std::vector<my_map_element>;
    

    那么构建一个向量并对其进行排序就非常简单了。在这里,我们为比较函数使用了一个模板,这使得在比较器中使用 lambda 变得更加容易:

    template<typename Functor>
    my_element_list sortMap(const my_map& the_map, Functor compare) {
        my_element_list v(the_map.begin(), the_map.end());
        std::sort(v.begin(), v.end(), compare);
        return v;
    }
    

    与您的代码不同,它返回排序列表。如果需要,呼叫者可以打印列表。例如,请参见示例 live on Coliru

    不过,这并不理想。如果地图的各个元素都非常复杂,那么制作一个指向元素的指针 向量可能比创建元素的副本更有效。除此之外,这不需要重新调整元素类型,这也使得对基本容器类型不可知论成为可能。但是,您需要记住,比较函子现在将接收指向要比较的元素的指针。见the modified example.

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多