gpt4 book ai didi

c++ - 如何使用具有用户定义结构的 C++ vector ?

转载 作者:行者123 更新时间:2023-11-27 22:51:42 26 4
gpt4 key购买 nike

我正在尝试使用 vector 管理结构数组,但一直收到错误消息。

vector 在头文件中声明为:

vector< TLE_Values, allocator<TLE_Values> > SavedSatellites;

VS2013 非常满意。

结构定义为:

struct TLE_Values
{
string CatalogNum;
string SatelliteName;
string DateStr;
string TimeStr;
string Classification;
double DecayValue;
int ElsetNum;
double InclinationValue;
double RaanValue;
double EccentricityValue;
double ArgPerigeeValue;
double PerigeeAngle;
double AvgSpeed;
double Period;
int OrbitNum;
};

并由构造函数使用默认值初始化。

在主程序代码中,确定了我需要的元素数量 (CountItemsInFile()),我尝试使用以下方法扩展 vector 列表:

SavedSatellites.push_back(CountItemsInFile());

然而,这会返回以下编译器错误消息:

error C2664: 
'void std::vector<TLE_Values,std::allocator<TLE_Values>>::push_back(const TLE_Values &)' : cannot convert argument 1 from 'int' to 'TLE_Values &&'
1> Reason: cannot convert from 'int' to 'TLE_Values'
1> No constructor could take the source type, or constructor overload resolution was ambiguous.

另一个线程建议 vector 需要用 0 初始化,这不会发生在像这样的用户定义类型中。我错过了什么?我哪里出错了?如何用我的结构创建初始 vector ?有很多关于使用 (int) 类型 vector 的文档,但如果您不使用整数,则文档不多。

最佳答案

扩展 vector 使用

SavedSatellites.resize(CountItemsInFile());

如果您只想为它保留内存但保持 vector 的大小不变并为后续的 push_back 做好准备而无需重新分配内存:

SavedSatellites.reserve(CountItemsInFile());

关于c++ - 如何使用具有用户定义结构的 C++ vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36620556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com