【问题标题】:How to convert tuple to byte array in c++11如何在 C++11 中将元组转换为字节数组
【发布时间】:2017-12-01 06:37:33
【问题描述】:

我需要编写一个函数来将元组转换为字节数组。 元组的类型可能包括int, long, double, std::string, char*等。 元组的大小和类型是任意的,比如

std:tuple<string, int, double> t1("abc", 1, 1.3);

std:tuple<char*, int, int, float, double, string> t2("abc", 1, 2, 1.3, 1.4, "hello");

我想使用这些元组作为输入,字节数组作为返回值。我该怎么办 ?

【问题讨论】:

  • 您的意思是要序列化和反序列化元组吗?
  • 转换为字节数组需要序列化并经常编组。没有单一的序列化格式,您必须先选择一种表示形式。
  • @BrianCain 当然我也暗示过
  • @BrianCain 实际上,我想将所有元组(作为多值键)值放在一个字节数组中,并将数组及其长度提供给标准 murmur3 算法以获得散列结果.那么,我能做什么?如何序列化元组,非常感谢。

标签: c++ arrays c++11 tuples byte


【解决方案1】:

还有出色的C++ API for message pack 原生支持元组

#include <string>
#include <sstream>
#include <tuple>

#include <msgpack.hpp>

int main() {
    auto t = std::make_tuple("1", 1, 1.0);
    auto buffer = std::stringstream{};

    // easy peezy
    msgpack::pack(buffer, t);
    auto tuple_as_string = buffer.str();
}

【讨论】:

    【解决方案2】:

    您可以将 Boost 序列化与 std::tuple 的小扩展一起用于此任务。但是,默认情况下它不会将其转换为字节数组,而是转换为其他内容。还有binary_oarchive。也许这符合您的需求。

    #include <fstream>
    #include <tuple>
    
    #include <boost/archive/text_oarchive.hpp>
    
    #include "serialize_tuple.h" // https://github.com/Sydius/serialize-tuple
    
    int main()
    {
      auto t = std::make_tuple(42,3.14,'a');
    
      std::ofstream ofs("test.dat");
      boost::archive::text_oarchive oa(ofs);
      oa << t;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      相关资源
      最近更新 更多