我正在尝试设置一个矢量来存储一组棒球投手。我想存储一个投手的名字Joe Smith(字符串)和他过去两年的平均收入 - 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;
}
答案 0 :(得分: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";
}
希望这个例子可以解决一些问题。
答案 1 :(得分:0)
你想要像
这样的东西vector<Pitcher*> *vecPit=new vector<Pitcher*>();
你添加
vecPit->push_back(new Pitcher("string", 2.123, 2.123)