我試圖設置一個矢量來存儲一組棒球投手。我想存儲一個投手的名字喬·史密斯(字符串)和他在過去兩年的平均得分--2.44和3.68。我還想存儲第二個投手的名字 - 鮑勃瓊斯(字符串)和他的平均得分5.22和4.78。這是一個較大的家庭作業的一部分,但我只是開始使用矢量。我遇到的問題是我的教科書說矢量只能用於存儲相同類型的值,而我找到的所有示例主要使用整數值。例如,我發現cplusplus.com這個例子在C++中設置矢量
// 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;
}
這種方式較好然後我的添加,您不使用指針,只是記住,如果你想保持這種活範圍結束後,您需要一個指針。 – Lefsler 2013-04-24 17:34:17
@demonofnight投手對象將被複制到矢量中,因此它們的作用域將與矢量的作用域相同。例如,如果矢量被返回,它將包含有效的投手對象。 – Porkbutts 2013-04-24 17:42:04
@Porkbutts更重要的一點是:鑑於'Pitcher'的定義,你應該永遠不會有指向它的指針。你可以使用'[]'(或迭代器,或者'back()'或者'front()')在向量中訪問它。如果你想保留在本地,你需要一份副本。 – 2013-04-24 18:14:17