繁体   English   中英

在堆栈上分配的结构的 C++ 向量

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

如果我们有一个结构指针MyInfo*的向量(分配在堆上)。 然后,我们可以检查vec[i] == NULL知道是否有在一个结构vec[i]这样, if (vec[i] != NULL) //then do some processing

但是,如果我们在堆栈上而不是在堆上分配MyInfo ,那么我们将得到如下所示的vector<MyInfo> 我猜每个 vec[i] 都是由 struct 默认构造函数初始化的。 你如何检查 vec[i] 是否包含一个类似于上述NULL指针情况的非空结构,比如if (vec[i] contains valid struct) //then do some processing

我的代码在下面

#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;
}

您可以使用一些选项。 第一个也是最简单的一个,是为结构的每个(或一个)变量定义一个值,这将表明结构尚未初始化。 在这种情况下, age应大于或等于 0,以便在逻辑上是直的。 因此,您可以将其初始化为 -1,如下所示:

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

现在,在您的主函数中,它将在age打印值 -1。 此外,您也可以将name变量的空值视为它的标志。

另一种方法可能是使用标志和获取/设置操作来指示变量何时初始化:

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;
}

您还可以在调用std::string name()函数的int age()时抛出异常,如果这些值尚未初始化:

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;
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM