简体   繁体   English

如何将 map 阵列塞入缓冲区以发送?

[英]How to cram map array in buffer to send?

I am trying to move the map array but for this I need to put everything in buffer, here is my code.我正在尝试移动 map 数组,但为此我需要将所有内容都放在缓冲区中,这是我的代码。

#include <iostream>
#include <map>
#include <string>

    std::map<std::int, std::string> maphack;
    maphack.emplace(1, "CS");
    maphack.emplace(2, "PBG");
    maphack.emplace(3, "Maicraft");
    maphack.insert_or_assign(3, "GTA5");

    for (auto &a : maphack) {
        std::cout << a.first << " : " << a.second << '\n';
    }

How to put everything above in the buffer?如何将上面的所有内容都放在缓冲区中?

char buffer[64];

send(sock, buffer, AmountToSend, 0);

The simple answer is to use std::ostringstream and std::istringstream which allows to use std streams machinery with a string storage.简单的答案是使用std::ostringstreamstd::istringstream ,它允许使用带有字符串存储的 std 流机器。 Which can be converted to char* with c_str() method if needed later, full example is below.如果以后需要,可以使用c_str()方法将其转换为char* ,完整示例如下。

The better answer can be to use more heavy lifting library for serialization, the choice of the format will depend on your program.更好的答案是使用更繁重的库进行序列化,格式的选择将取决于您的程序。 Do you need binary or text format?您需要二进制还是文本格式? Do you want other programs (in other programming languages) be able to read it?您是否希望其他程序(使用其他编程语言)能够阅读它? Do you need to support different endian system?您需要支持不同的字节序系统吗? Do you need to handle error when deserializing malformed input?反序列化格式错误的输入时是否需要处理错误? Boost, Qt, google protobuf, and other ones are out there. Boost、Qt、google protobuf 和其他的都在那里。

#include <iostream>
#include <map>
#include <sstream>
#include <string>

void write_map(const std::map<int, std::string> &m, std::ostream &out) {
  for (auto &a : m) {
    out << a.first << " " << a.second << '\n';
  }
}

std::map<int, std::string> read_map(std::istream &in) {
  std::map<int, std::string> m;
  int i;
  std::string s;
  while (in >> i >> s) {
    m.emplace(i, s);
  }
  return m;
}

int main() {
  std::map<int, std::string> m;
  m.emplace(1, "CS");
  m.emplace(2, "");
  m.emplace(3, "Maicraft");
  m.insert_or_assign(3, "GTA5");

  std::ostringstream out;
  write_map(m, out);
  std::string data = out.str();
  std::cout << "Data:\n" << data << std::endl;

  // send data over socket
  // ...

  std::istringstream in(data);
  auto m1 = read_map(in);
  std::cout << "Read:\n";
  write_map(m1, std::cout);
  std::cout << std::endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM