If we have a vector of struct pointer MyInfo*
(allocated on heap). Then we can check vec[i] == NULL
to know whether there is a struct in the vec[i]
, like this, if (vec[i] != NULL) //then do some processing
However, if we allocate MyInfo
on stack instead of on heap, then we have vector<MyInfo>
as shown below. I guess each vec[i] is initialized by the struct default constructor. How do you check whether vec[i] contains a non-empty struct similar to above NULL
pointer case, like if (vec[i] contains valid struct) //then do some processing
My code is below
#include <iostream> // std::cout
#include <string>
#include <vector>
using namespace std;
struct MyInfo {
string name;
int age;
};
int main () {
vector<MyInfo> vec(5);
cout << "vec.size(): " << vec.size() << endl;
auto x = vec[0];
cout << x.name << endl; //this print "" empty string
cout << x.age << endl; //this print 0
return 0;
}
See Question&Answers more detail:os