[Solved] C++ vector of struct allocated on stack


There are some options you can use. The first and easiest one, is to define a value to each (or for one) of your struct’s variables, that will point that the struct is not initialized yet. In this case, age should be large or equal to 0, to be logicly straight. So, you can initialize it to -1, like this:

struct MyInfo {
    string name;
    int age = -1;
};
// Or
struct MyInfo {
    string name;
    int age;
    MyInfo() : name(""), age(-1) {} // Use constructor
};

Now, in your main function, it will print in the age the value -1. Also, you can see the empty of the name variable as a sign for it too.

Another way might be using flag and get/set operations to indicate when the variables are initialize:

struct MyInfo {
private:
    std::string _name;
    int _age;
    bool age_initialize = false;
    bool name_initialize = false;

public:
    void name(const std::string &name_p) { _name = name_p; name_initialize = true; }
    void age(int age_p) { _age = age_p; age_initialize = true; }
    void init(int age_p, const std::string &name_p) { age(age_p); name(name_p); }
    bool is_initialize() { return name_initialize && age_initialize; }
    int age() { return _age; }
    std::string name() { return _name; }
};

int main() {
    std::vector<MyInfo> vec(5);
    std::cout << "vec.size(): " << vec.size() << std::endl;

    auto x = vec[0];
    std::cout << x.is_initialize() << std::endl; //this print 0
    std::cout << x.name() << std::endl; //this print "" empty string
    std::cout << x.age() << std::endl; //this print 0

    return 0;
}

You can also throw an exception when calling int age() of std::string name() function, if those values are not initialize yet:

struct MyInfo {
private:
    /* ... */

public:
    /* ... */
    int age() {
        if (!age_initialize) throw std::runtime_error("Please initialize age first.");
        return _age;
    }
    std::string name() {
        if (!name_initialize) throw std::runtime_error("Please initialize name first.");
        return _name;
    }
};

solved C++ vector of struct allocated on stack