You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中创建并填充结构体vector?

问题分析与解决方案

你的代码中push_back("" , 0 , true);是错误用法,vector<animalS>的push_back方法需要接收一个animalS类型的对象,而非三个独立参数。下面是几种正确填充vector的实现方式:

方法1:聚合初始化临时对象传入

C++11及以上版本支持结构体的聚合初始化,可直接在push_back中构造临时对象:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct animalS
{
    string animalType = "none";
    int animalCount = 0;
    bool animalEndangered = false;
};

int main()
{
    vector<animalS> animal;

    // 用聚合初始化构造临时对象并加入vector
    animal.push_back({"Tiger", 500, true});
    animal.push_back({"Deer", 100000, false});
}

方法2:先实例化对象赋值,再加入vector

如果需要分步设置结构体成员,可先创建对象赋值,再调用push_back:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct animalS
{
    string animalType = "none";
    int animalCount = 0;
    bool animalEndangered = false;
};

int main()
{
    vector<animalS> animal;

    // 实例化对象并赋值
    animalS panda;
    panda.animalType = "Giant Panda";
    panda.animalCount = 1864;
    panda.animalEndangered = true;
    // 将对象加入vector
    animal.push_back(panda);
}

方法3:用emplace_back直接在vector内构造对象

emplace_back会直接在vector的内存空间中构造结构体对象,无需创建临时对象,效率更高:

#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct animalS
{
    string animalType = "none";
    int animalCount = 0;
    bool animalEndangered = false;
};

int main()
{
    vector<animalS> animal;

    // 直接在vector中构造对象
    animal.emplace_back("Elephant", 415000, false);
    animal.emplace_back("Rhino", 27000, true);
}

内容的提问来源于stack exchange,提问作者Kunedia Aoi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:30:42