1

我已经声明了地图:

std::map <std::string, int> mymap;

我想在上面的地图中插入两个值, *vit然后hit->first通过套接字发送和接收。

我的代码:

for (std::map < int, std::vector < std::string > >::iterator hit = three_highest.begin(); hit != three_highest.end(); ++hit) {

for (std::vector < std::string >::iterator vit = (*hit).second.begin(); vit != (*hit).second.end(); vit++) {
        std::cout << hit->first << ":";
        std::cout << *vit << "\n";
        mymap.insert( std::pair<std::string,int> (*vit,hit->first)); //Is it correct way
       }
    }

//然后通过socket发送

if ((bytecount = send(*csock, mymap ,  sizeof(mymap), 0)) == -1) { // I think this is wrong, Can someone correct it?
    fprintf(stderr, "Error sending data %d\n", errno);
    goto FINISH;
    }

在接收端如何取回这两个变量?

std::map <std::string, int> mymap;
if((bytecount = recv(hsock, mymap, sizeof(mymap), 0))== -1){   //Needs help here also

// getting mymap->first, mymap->second.

        fprintf(stderr, "Error receiving data %d\n", errno);
        }
4

2 回答 2

2

就像我在评论中所说的那样,任何包含指针、文件/套接字句柄和类似的数据结构都不能通过网络发送,也不能保存到文件中。至少不是没有任何编组序列化

在你的情况下,它可以是简单的一半。您需要做的第一件事是发送地图的大小,即其中的条目数。这有助于在接收方重新创建地图。

然后您可以先发送所有键,然后发送所有值。发送值很简单,只需将它们放在 a 中std::vector并使用 egstd::vector::data来获取指向实际数据的指针。发送密钥有点复杂(因为它们可能有不同的长度)。对于密钥,您可以制作一个足以容纳所有密钥字符串的固定大小数组的数组,然后发送它。或者您可以一个一个地发送每个密钥,接收方检查字符串终止符。或者一个一个地发送字符串,首先是字符串的长度,然后是实际的字符串。

于 2013-09-04T09:25:20.937 回答
2

您的解决方案可以很简单,例如发送一个键后跟一个 NUL,然后是一个值,然后是一个 NUL,然后重复此操作,直到您到达最后,然后发送一个额外的 NUL。

但是你必须自己迭代地图,然后自己重​​建它。

于 2013-09-04T09:26:08.017 回答