2

我正在尝试设置一个向量来存储一组棒球投手。我想存储一个投手的名字 Joe Smith(字符串)和他过去两年的平均得分 - 2.44 和 3.68。我还想存储第二个投手的名字 - Bob Jones(字符串)和他的平均得分 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;
}
4

2 回答 2

5

好吧,我想你想存储一个投手向量

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

希望这个例子能澄清一些事情。

于 2013-04-24T17:33:12.040 回答
0

你想要类似的东西吗

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

你加上

vecPit->push_back(new Pitcher("string", 2.123, 2.123)
于 2013-04-24T17:33:26.837 回答