最好的结构存储的东西像数组样式与保持恒定访问时间任何元素是矢量。它就像你有动态大小的数组。
第二个选择是deque。如果你计划拥有非常多的数据,因为它具有更好的存储管理能力,并且你可以从前面和后面编辑它,而不是像向量一样编辑它。
最后一个可能是列表。如果您计划对数据进行大量编辑,例如删除插入新元素(而不仅仅是访问它们),则应该考虑这一点,因为它在插入/擦除元素时具有线性复杂性,而前2个元素具有线性加上额外的线性时间位置和结束之间的元素数量。
所以结论:
- 载体 - 最简单的
- 双端队列 - 好大的数据存储
- 列表 - 良好的储存
的大EDITTING这些都是STL序列容器和包括的标题应该看起来像:
#include <vector>
here's reference for all STL containers
编辑︰ 我看到你的意思是别的,但我留在这里,并添加到它。
你真的需要消费类吗?我的意思是,如果将所有关于Line的数据都保留在Line类中,那将更合乎逻辑。这意味着如果需要,我会将每个月使用的服务存储在向量中,或者我会立即计算价格并记住上个月的服务。我也会做一个叫做program的类来存储使用的服务,并让它处理使用的服务的数量。如果已经有2个服务,它可以丢弃新的服务,或者重写旧的服务。你也可以让程序返回价格,然后乘以使用时间。事情是这样的:
#include <vector>
using namespace std;
class Service{
public:
int getPrice(){return monthPrice;}
void setPrice(const int &p) { monthPrice = p; }
private:
int monthPrice;
};
class Program{
public:
Program(){servicesUsed = 0; monthTime = 0;}
Program(const int &t) : monthTime(t) {servicesUsed = 0;}
void setTime(int t){monthTime = t;}
void addService(Service &s);
int price(); //calculate price of program
private:
int monthTime; //time that program was used
Service services[2]; //services used in program
int servicesUsed;
};
void Program::addService(Service &s){
if(servicesUsed < 2){ // Discarding solution
services[servicesUsed] = s;
servicesUsed++;
}
}
int Program::price(){
int pP = 0;
for(int i = 0; i < servicesUsed; i++){
pP += services[i].getPrice();
}
pP *= monthTime;
return pP;
}
class Line{
public:
Program *addMonth(const int &t); //will return handle for month
int consuption(); //calculate full line consuption
private:
vector<Program> monthList; //store data about services per month
};
Program *Line::addMonth(const int &t){
monthList.push_back(Program(t));
return &monthList.back();
}
int Line::consuption(){
int p = 0;
for(unsigned int i = 0; i < monthList.size(); i++){
p += monthList[i].price();
}
return p;
}
int main(){
//showcase
Program *handle;
Service s1,s2,s3;
s1.setPrice(50);
s2.setPrice(75);
s3.setPrice(100); //probably read from file
Line line;
handle = line.addMonth(30); // monthTime probably also from file
handle->addService(s1);
handle->addService(s2);
handle->addService(s3);
handle = line.addMonth(60);
handle->addService(s3);
handle->addService(s2);
int p = line.consuption();
return 0;
}
应该工作正常altought你可能需要更多的修改它;)
这很大程度上取决于你想要在'Consumption`对象集合上执行什么操作。你想随机访问?你想要插入吗?收藏上典型的行为是什么? – sharptooth 2011-01-12 13:54:27
基本上,当为某一行制作帐单时,需要运行集合以识别每个消费的行和服务,然后添加与行号匹配的行,并在添加行时确保一切都得到尊重(不超过2个服务/行/月等)..所以我正在寻找最好的方式来组织这 – meno 2011-01-12 15:14:51