在c++中设置向量

Setting up a vector in C++

本文关键字:向量 设置 c++      更新时间:2023-10-16

我试图设置一个向量来存储一组棒球投手。我想存储一个投手的名字乔史密斯(字符串)和他的自责分率在过去的两年- 2.44和3.68。我还想存储第二个投手的名字-鲍勃琼斯(字符串)和他的自责分率5.22和4.78。这是一个更大的家庭作业的一部分但我才刚刚开始使用向量。我遇到的问题是,我的课本上说,向量只能用来存储相同类型的值,我找到的所有例子都主要使用整数值。例如,我在cplusplus.com上找到了这个例子

// constructing vectors
#include <iostream>
#include <vector>
int main ()
{
unsigned int i;
// constructors used in the same order as described above:
std::vector<int> first;                                // empty vector of ints
std::vector<int> second (4,100);                       // four ints with value 100
std::vector<int> third (second.begin(),second.end());  // iterating through second
std::vector<int> fourth (third);                       // a copy of third
// the iterator constructor can also be used to construct from arrays:
int myints[] = {16,2,77,29};
std::vector<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are:";
for (std::vector<int>::iterator it = fifth.begin(); it != fifth.end(); ++it)
std::cout << ' ' << *it;
std::cout << 'n';
return 0;
}

有什么方法可以改变这段代码接受一个字符串和两个双精度?我不需要从用户那里获得任何输入,我只需要在int main()中初始化两个投手。我已经为它们设置了一个类,如下所示,但是赋值需要一个向量。

#ifndef PITCHER_H
#define PITCHER_H
#include <string>
using namespace std;
class Pitcher
{
private:
    string _name;
    double _ERA1;
    double _ERA2;
public:
    Pitcher();
    Pitcher(string, double, double);
    ~Pitcher();
    void SetName(string);
    void SetERA1(double);
    void SetERA2(double);
    string GetName();
    double GetERA1();
    double GetERA2();       
};
#endif
#include "Pitcher.h"
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
Pitcher::Pitcher()
{
}
Pitcher::Pitcher(string name, double ERA1, double ERA2)
{
_name = name;
_ERA1 = ERA1;
_ERA2 = ERA2;
}
Pitcher::~Pitcher()
{
}
void Pitcher::SetName(string name)
{
_name = name;
}
void Pitcher::SetERA1(double ERA1)
{
_ERA1 = ERA1;
}
void Pitcher::SetERA2(double ERA2)
{
_ERA2 = ERA2;
}
string Pitcher::GetName()
{
return _name;
}
double Pitcher::GetERA1()
{ 
return _ERA1;
}
double Pitcher::GetERA2()
{
return _ERA2;
}
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include "Pitcher.h"
using namespace std;
int main()
{
Pitcher Pitcher1("Joe Smith", 2.44, 3.68);
cout << Pitcher1.GetName() << endl;
cout << Pitcher1.GetERA1() << endl;
cout << Pitcher1.GetERA2() << endl;
system("PAUSE");
return 0;
}

我认为你想要存储投手向量

 vector<Pitcher> pitchers;
 Pitcher p1("name", 0.5, 0.1); //create a pitcher
 pitchers.push_back(p1); //add the pitcher to the vector
 ...//fill in some other pitchers
 //to print all the pitchers
 for(unsigned i = 0; i < pitchers.size(); ++i)
 {
      cout << pitchers[i].GetName() << " " << pitchers[i].GetERA1() << "n";
 }

您想要像

vector<Pitcher*> *vecPit=new vector<Pitcher*>();

加上

vecPit->push_back(new Pitcher("string", 2.123, 2.123)