在结构中初始化空向量 - C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13434937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Initialize empty vector in structure - c++
提问by Tomasz
I have a struct
:
我有一个struct
:
typedef struct user {
string username;
vector<unsigned char> userpassword;
} user_t;
I need to initialize userpassword
with an empty vector
:
我需要userpassword
用空初始化vector
:
struct user r={"",?};
What should I put instead of ?
?
我应该用什么代替?
?
回答by Dietmar Kühl
Both std::string
and std::vector<T>
have constructors initializing the object to be empty. You could use std::vector<unsigned char>()
but I'd remove the initializer.
双方std::string
并std::vector<T>
有构造函数初始化对象设置为空。您可以使用,std::vector<unsigned char>()
但我会删除初始化程序。
回答by Kerrek SB
Like this:
像这样:
#include <string>
#include <vector>
struct user
{
std::string username;
std::vector<unsigned char> userpassword;
};
int main()
{
user r; // r.username is "" and r.userpassword is empty
// ...
}
回答by Luchian Grigore
How about
怎么样
user r = {"",{}};
or
或者
user r = {"",{'user r = {"",std::vector<unsigned char>()};
'}};
or
或者
user r;
or
或者
struct user r = { string(), vector<unsigned char>() };
回答by dma
The default vector constructor will create an empty vector. As such, you should be able to write:
默认向量构造函数将创建一个空向量。因此,您应该能够编写:
class User {
User() {}
string username;
vector<unsigned char> password;
};
Note, I've also used the default string constructor instead of "".
请注意,我还使用了默认字符串构造函数而不是“”。
You might want to consider making user a class and adding a default constructor that does this for you:
您可能需要考虑使用户成为一个类并添加一个默认构造函数来为您执行此操作:
User r;
Then just writing:
然后只写:
##代码##Will result in a correctly initialized user.
将导致正确初始化用户。