c++ - 你如何制作类对象的 vector ?

标签 c++ vector

我对 vector 的工作原理有点困惑。我想要做的是创建一个包含 5 个 TaxBill 对象的 vector 。然后,我想要做的是从一个输入文件中读取,该文件包含 5 个州的名称和不同的税率。我想在 int main() 中的数组中存储对象中的州名称和州的税率。

这是名为“Tax Rates.dat”的输入文件。这些数字分别是每个州的销售税、属性(property)税和所得税率。

TEXAS      .0825 .02 -.03
MARYLAND   .065 .04 .05
OHIO       .03 .025 .03
CALIFORNIA .095 .055 .045
MAINE      .02 .015 .02

这是我的类接口(interface)“Tax Bill.h”。

using namespace std;

class TaxBill
{
public:
      void setValue(string, int);
      void dataValid(double&, double&, double&);

private:
      string Name;
      int index;
      double taxBill;
}

这是我的名为“Tax Bill.cpp”的类实现。

#include "Tax Bill.h"

void TaxBill::setValue(string name, int x)
{}


void TaxBill::dataValid(double& a, double& b, double& c)
{
      if(a < 0)
            a = 0;
      if(b < 0)
            b = 0;
      if(c < 0)
            c = 0;

      return;
}

到目前为止,这是我的主要源代码。

#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <vector>
#include "Tax Bill.h"

using namespace std;


int main()
{
      const int SALARY = 100000,
            HOUSE = 246000,
            PURCHASE = 36000;
      ifstream fin;
      fin.open("Tax Rates.dat");
      vector <TaxBill> someVector (5);
      double sales,
            property,
            income;
      double taxRates[5][3];
      string name;

      if(!fin)
            return 0;
      else
      {
            for(int i = 0; fin >> name >> sales >> property >> income; i++)
            {
                  dataValid(sales, property, income);
                  taxRates[i][0] = sales;
                  taxRates[i][1] = property;
                  taxRates[i][2] = income;
            }
      }

for 循环是我想将从输入文件和 i 读取的状态名称存储到字符串 Nameindex 类对象。索引的原因是因为在程序的后面我想按字母顺序对 vector 中的对象进行排序,而不是存储相应税率的数组。

我也不想使用函数 push_back()

我想我的问题是,如何创建一个包含 5 个类对象的 vector 并访问它们?

请记住,我的程序还没有完成,正是这一障碍阻碍了我。

最佳答案

此处是使用代码中的 vector 的示例。在这里声明

vector <TaxBill> someVector (5);

现在,您有 someVector[0] - [4](总共 5 个)。要使用它,实际上您只需像普通数组一样分配它。

someVector[0].{insert property here}

但是等等,在你的类中,没有明确的方法来设置字符串名称和索引。所以我想你忘了把它放在这里,所以我在类里面自己做了。

class TaxBill
{
public:
      void setValue(string Name, int Index){
         name = Name; index = Index;
      }
      void dataValid(double&, double&, double&);

private:
      string name;
      int index;
      double taxBill;
}

现在要使用 vector ,我只是这样使用属性

someVector[0].setValue("someName",1);

Tada,你让它发挥作用。顺便说一句,我不知道你为什么要在类中声明一个过程,但你想在主程序中多次使用它。我是说这个

dataValid(sales, property, income);

要使用它,我建议您在主程序中而不是在类中创建一个过程,无论如何该行都会产生错误。 :)

关于c++ - 你如何制作类对象的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35689763/

相关文章:

c++ - 由于 emmintrin.h,即使使用 -msse2 标志,Clang-cl 也无法构建 NSS lib

c++ - spoj 上的抗印迹系统

C++ -- Detours (Win32 API Hijacking) -- 劫持类方法

c++ - 从 C++ 中的二维 vector 中的特定索引获取值

尝试获取点积的 C# 错误

c++ - 如何绘制存储在 vector 中的 SFML 形状

c++ - 将一张位图的一部分复制到 ImageList 中

c++ - 开关语句和整数模板值

c++ - 访问Inventory.h中的迭代器、 vector

r - 将矩阵与R中的向量等同是什么意思