gpt4 book ai didi

c++ - 在 C++ 中设置 vector

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:24 25 4
gpt4 key购买 nike

我正在尝试设置一个 vector 来存储一组棒球投手。我想存储一个投手的名字乔史密斯(字符串)和他过去两年的平均得分 - 2.44 和 3.68。我还想存储第二个投手的名字 - Bob Jones(字符串)和他的平均得分 5.22 和 4.78。这是一个更大的家庭作业的一部分,但我才刚刚开始使用 vector 。我遇到的问题是我的教科书说 vector 只能用于存储相同类型的值,而我发现的所有示例主要使用整数值。例如我在 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;
}

有什么方法可以更改此代码以接受一个字符串和两个 double ?我不需要从用户那里获得任何输入我只需要在 int main() 中初始化两个投手。我已经为他们设置了一个类,如下所示,但分配需要一个 vector 。

#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

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

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

关于c++ - 在 C++ 中设置 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com