Frage

Having

struct addrinfo {
           int              ai_flags;
           int              ai_family;
           int              ai_socktype;
           int              ai_protocol;
           socklen_t        ai_addrlen;
           struct sockaddr *ai_addr;
           char            *ai_canonname;
           struct addrinfo *ai_next;
};
typedef struct addrinfo* PADDRINFOA;

the only way I've found to represent it (thanks to Jefffrey) as std::vector is to declare

typedef struct sAddrInfo{
    int              ai_flags;
    int              ai_family;
    int              ai_socktype;
    int              ai_protocol;
    socklen_t        ai_addrlen;
    struct sockaddr *ai_addr;
    char            *ai_canonname;
    //no next pointer
}NoListAddrInfo;

and then

PADDRINFOA next = myAddrInfo;
ret->addr_vect.clear();
for(size_t i = 0;next != NULL;i++)
{
    ret->addr_vect.push_back(sAddrInfo());
    ret->addr_vect[i].ai_flags = next->ai_flags;
    ret->addr_vect[i].ai_family = next->ai_family;
    ret->addr_vect[i].ai_socktype = next->ai_socktype;
    ret->addr_vect[i].ai_protocol = next->ai_protocol;
    ret->addr_vect[i].ai_addrlen = next->ai_addrlen;
    ret->addr_vect[i].ai_addr = next->ai_addr;
    next = next->ai_next;
}

Is there any way to do this using less instructions?

War es hilfreich?

Lösung

In any case your structure should look like this:

struct addrinfo {
   int              ai_flags;
   int              ai_family;
   int              ai_socktype;
   int              ai_protocol;
   socklen_t        ai_addrlen;
   struct sockaddr *ai_addr;
   char            *ai_canonname;
   // notice the lack of `ai_next`
};

Then if you really want to keep the linked list you should either use std::forward_list or std::list (doubly linked list):

std::forward_list<addrinfo> list;

otherwise if you want to use an std::vector (which from your example usage would fit nicely) you would just need to change it to:

std::vector<addrinfo> vector;

Andere Tipps

Structs are just classes.

std::vector<addrinfo> myvec;
myvec.push_back(addrinfo());
myvec[0].ai_flags = 42;

If you are asking how to put one of those structs in a vector...

typedef struct addrinfo ADDRINFO;

std::vector<ADDRINFO> myvec;

myvec.push_back(ADDRINFO());

myvec[0].ai_flags= 42;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top