[c++] Initialize empty vector in structure - c++

I have a struct:

typedef struct user {
    string username;
    vector<unsigned char> userpassword;
} user_t;

I need to initialize userpassword with an empty vector:

struct user r={"",?};

What should I put instead of ??

This question is related to c++ vector

The answer is


How about

user r = {"",{}};

or

user r = {"",{'\0'}};

or

user r = {"",std::vector<unsigned char>()};

or

user r;

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

The default vector constructor will create an empty vector. As such, you should be able to write:

struct user r = { string(), vector<unsigned char>() };

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:

class User {
  User() {}
  string username;
  vector<unsigned char> password;
};

Then just writing:

User r;

Will result in a correctly initialized user.