如何通过访问对象来计算二维向量的总和
Posted
技术标签:
【中文标题】如何通过访问对象来计算二维向量的总和【英文标题】:How to calculate sum of 2d vector by accessing objects 【发布时间】:2020-05-30 22:24:12 【问题描述】:我正在执行一项任务,我们必须制造车辆,将它们存放在陈列室中,然后将陈列室存放在经销商处。要做的事情我已经建立了,vector(Vehicle) carVector;在“Showroom.h”中,和vector(vector(Vehicle)) showroomVector;在“Dealsership.h”中
目前我正在尝试在经销商处显示汽车的平均价格。我目前的功能是这样的
float Dealership::GetAveragePrice()
vector<vector<Vehicle>> showroomVector;
float sum = 0.0f;
float avgSum = 0.0f;
unsigned int i;
unsigned int j;
for (i = 0; i < showroomVector.size(); i++)
for (j = 0; j < showroomVector.at(i).size(); j++)
sum = sum + showroomVector.at(i).at(j).GetPrice;
avgSum = sum/((float)(i*j));
return avgSum;
getprice函数在Vehicle.cpp中,如下
float Vehicle::GetPrice()
return this->price;
我基本上需要将所有陈列室中每辆车的价格相加,然后除以 i*j 以找到经销商的平均值,但我无法正确访问二维向量中的数据
增加陈列室的功能(在cmets中提到)
void Dealership::AddShowroom(Showroom s)
if (showroomVector.size() == capacity)
cout << "Dealership is full, can't add another showroom!\n";
else if (showroomVector.size() < capacity)
vector<Vehicle> s;
showroomVector.push_back(s);
【问题讨论】:
您的示例代码根本没有将任何项目放入局部变量showroomVector
,因此总和应该为0。
sum = sum + showroomVector.at(i).at(j).GetPrice;
在最后的函数调用中缺少()
。
showroomVector.at(i).at(j).GetPrice;
正在尝试将指针添加到您的总和。不确定这是复制粘贴错误还是什么。
在你显示的代码中vector<Vehicle> s;
被添加为空
还要保留 (),它们在函数调用中是必需的,否则您将传递函数指针。
【参考方案1】:
您的代码有点混乱,vector<vector<Vehicle>> showroomVector;
应该是类成员而不是函数成员。
如上所述,GetPrice
在调用中缺少括号。
Showroom s
参数从不在AddShowroom
函数中使用。
这是一个简化的可能实现,它对某些 cmets 有意义:
Live demo
#include <iostream>
#include <vector>
class Vehicle
float price;
public:
Vehicle(int price) : price(price) //ctor for sample
float GetPrice()
return this->price;
;
//for test purposes
class Showroom
public:
std::vector<Vehicle> vehicles = Vehicle(500), Vehicle(1000), Vehicle(2350);
;
class Dealership
std::vector<std::vector<Vehicle>> showroomVector;
size_t capacity = 15;
public:
//your function, unaltered, except for the brackets
float GetAveragePrice()
float sum = 0.0f;
float avgSum = 0.0f;
unsigned int i = 0;
unsigned int j = 0;
for (i = 0; i < showroomVector.size(); i++)
for (j = 0; j < showroomVector.at(i).size(); j++)
sum = sum + showroomVector.at(i).at(j).GetPrice();
avgSum = sum / ((float)(i * j));
return avgSum;
//Showroom parameter is never used
//a logic move would be to have a vector of vehicles in each showroom
void AddShowroom(Showroom s)
if (showroomVector.size() == capacity)
std::cout << "Dealership is full, can't add another showroom!\n";
return;
if (showroomVector.size() < capacity) //add all prices of vehicles in showroom
showroomVector.push_back(s.vehicles);
;
int main()
Dealership d;
Showroom s;
d.AddShowroom(s); //add a showroom
Showroom s2;
d.AddShowroom(s); //add another
std::cout << d.GetAveragePrice();
return EXIT_SUCCESS;
【讨论】:
以上是关于如何通过访问对象来计算二维向量的总和的主要内容,如果未能解决你的问题,请参考以下文章