[英]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. colIndex包含字符串向量。 Say the 3rd element here is the uiVersionNumber data.
假设这里的第三个元素是uiVersionNumber数据。 How do I copy the 3rd element which is a string to the struct member uiVersionNumber which is also of string datatype.
如何将作为字符串的第三个元素复制到同样是字符串数据类型的结构成员uiVersionNumber 。 Thanks in advance.
提前致谢。
You can access elements of a vector like in a C-array or use the at()
method of vector
您可以像在 C 数组中一样访问向量的元素或使用
vector
的at()
方法
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我假设第三个元素,你的意思是
index = 2
,相应地改变
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()};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.