Catty
Catty

Reputation: 466

Insert data into std::map <std::string, int> mymap from two different data structure and sending it via socket

I have declared map:

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

I want to insert two values in above map *vit and hit->first and then sending and receiving via socket.

My code:

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
       }
    }

//Then send via 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;
    }

And at receiving end how to get those two variables back?

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);
        }

Upvotes: 1

Views: 814

Answers (2)

xaxxon
xaxxon

Reputation: 19761

Your solution can be something as simple as sending a key followed by a NUL then the value followed by a NUL and repeating that until you get to the end and then sending an extra NUL.

But you have to iterate over the map yourself and then reconstruct it yourself as well.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409196

Like I said in my comment, any kind of data structure containing pointers, file/socket handles and similar, can't be sent over the network, or saved to file. At least not without any kind of marshalling or serialization.

In your case it can be half simple. The first thing you need to do is send the size of the map, i.e. the number of entries in it. This helps in recreating the map on the receiving side.

Then you can first send all the keys, followed by all the values. Sending the values is simple, just put them in a std::vector and use e.g. std::vector::data to get a pointer to the actual data. Sending the keys is a little more complicated (since they may have different lengths). For the key, you can either make an array of fixed-size arrays big enough to fit all the key strings, and send that. Or you can send each key one by one with the receiving side checking for the string terminator. Or send the strings one by one, with the length of the string first followed by the actual string.

Upvotes: 2

Related Questions