简体   繁体   中英

Copying vector<string> data into struct data member in C++

This is my struct:

typedef struct
{

    string uiVersionNumber;

    unsigned long uiTimeStamp;

}Req_Port;

The vector is defined like this:

std::vector<string> colIndex;

The colIndex contains vector of strings. Say the 3rd element here is the uiVersionNumber data. How do I copy the 3rd element which is a string to the struct member uiVersionNumber which is also of string datatype. Thanks in advance.

You can access elements of a vector like in a C-array or use the at() method of vector

So you can do:

Req_Port.uiVersionNumber = colIndex.at(2);
// Req_Port.uiVersionNumber = colIndex[2]; does not check for out-of-bound errors

I assumed that by 3rd element, you mean index = 2 , change that accordingly

While you create an instance of your struct, the default constructor called. You can pass the 3rd element of the vector to the default constructor.

Req_Port reqPtr{colIndex.at(2),colIndex.at(2).size()};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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