创建 boost::tuple<std::string、std::string、int> 和 std::vector <int>的映射

Creating map of boost::tuple<std::string, std::string, int>and std::vector<int>

本文关键字:std int gt string lt 映射 vector boost 创建 tuple      更新时间:2023-10-16

我想创建一个map, Key是两个字符串和一个int的组合,value可以是基于Key的多个int。所以我试着创建boost::tupleand std::vector的映射。我试着像下面这样编写示例程序:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <string>
#include <boost/tuple/tuple.hpp>
#include <boost/unordered_map.hpp>
using namespace std;
typedef boost::tuple<std::string, std::string, int> tpl_t;
struct key_hash : public std::unary_function<tpl_t, std::size_t>
{
    std::size_t operator()(const tpl_t& k) const
    {
        return boost::get<0>(k)[0] ^ boost::get<1>(k)[0] ^ boost::get<2>(k);
    }
};
struct key_equal : public std::binary_function<tpl_t, tpl_t, bool>
{
    bool operator()(const tpl_t& v0, const tpl_t& v1) const
    {
        return (
                 boost::get<2>(v0) == boost::get<2>(v1) &&
                 boost::get<0>(v0) == boost::get<0>(v1) &&
                 boost::get<1>(v0) == boost::get<1>(v1)               
               );
   }
};
typedef boost::unordered_map<tpl_t, std::vector<int>, key_hash,key_equal> map_t;
void function1(map_t& myMap, std::string file, std::string txt, int num1, int num2)
{
    tpl_t key = boost::make_tuple(file, txt, num1);
    map_t::iterator itr = myMap.find(key);
    if(itr != myMap.end())
    {
        itr->second.push_back(num2);
    }
    else
    {
        std::vector<int> num2Vec;
        num2Vec.push_back(num2);
        myMap.insert(std::make_pair(boost::make_tuple(file,txt,num1),num2Vec));
    }   
}
int main()
{
    map_t myMap;
    function1(myMap, "file1", "text", 5, 10);
    function1(myMap, "file1", "text_t", 5, 30);
    function1(myMap, "file2", "text", 5, 50);
}

这个程序工作很好,但我想知道是否有更好的方法来做到这一点。我担心的性能,因为地图的大小可以增长到任何东西。我还没有测量过性能。

谢谢,
Shrik

我担心性能,因为映射的大小可以增长到任何东西。我还没有测量过性能。

在您担心您的设计不适合任务的可能性之前,您应该考虑是否有适当的性能度量。

设计一些用例,并创建一个样本数据分布——组合键和值的常见用例,每一边的标准偏差,以及尾部。不仅要考虑数据集本身,还要考虑它的设置和使用配置文件——插入、搜索和删除的频率。

也就是说,总的来说,您将组合键建模为元组的方法是明智的,尽管主观上,我更喜欢一个结构体,但这是一个非常小的评论。

对于值-考虑使用多映射而不是带有向量的映射,这可能会更快,但这取决于值的数量。

这里还有一些需要考虑的事情:

  • 你的(多)地图必须是有序的还是无序的?根据使用配置文件的不同,无序的地图可以明显更快。
  • 你能调整你的关键知识,使比较更快吗?例如,如果字符串很长并且是静态的(例如,几乎总是"file1"),您是否可以通过先计算两个比较键的整数部分来获益?
  • 您是否可以通过使用分层映射而不是具有复合键的映射来获益?

最好使用构成程序测试套件一部分的示例数据和场景来回答上面的许多问题。这样,您就可以在更改数据结构时观察性能的变化。

相关文章: