[英]How do I add an enumeration type to reference an array
我的猜測是。 但是,我看到的所有示例都創建了一個item_type實例,即item_type_instance。 但是我的情況更簡單...我想為數組提供一些描述性的信息,而不僅僅是使用0和1。
enum item_type {weight, cost};
然后將權重和成本替換為0和1。
void algo(int cost_low,int cost_high,int throw_weight, int item_id)
{
int quantity,remainder;
quantity=throw_weight/item_matrix[item_id][0];
remainder=throw_weight%item_matrix[item_id][0];
if(remainder==0)
{
cost_low=(quantity-1)*item_matrix[item_id][1];
cost_high=quantity*item_matrix[item_id][1];
throw_weight-=(quantity-1)*item_matrix[item_id][0];
}
else
{
cost_low=quantity*item_matrix[item_id][1];
cost_high=(quantity+1)*item_matrix[item_id][1];
throw_weight-=quantity*item_matrix[item_id][0];
}
}
你當然可以做到; 但你不會,而代表item
在S item_matrix
的東西不是一個數組更有意義?
struct Item {
int weight;
int cost;
};
這可能會使您的算法更具可讀性:
void algo(int cost_low,int cost_high,int throw_weight, int item_id)
{
int quantity,remainder;
Item& item = item_matrix[item_id];
quantity=throw_weight/item.weight;
remainder=throw_weight%item.weight;
if(remainder==0)
{
cost_low=(quantity-1)*item.cost;
cost_high=quantity*item.cost;
throw_weight-=(quantity-1)*item.weight;
}
else
{
cost_low=quantity*item.cost;
cost_high=(quantity+1)*item.cost;
throw_weight-=quantity*item.cost;
}
}
甚至可以進一步重構,並將計算委托給Item
。
-編輯我無法抗拒...這是可以委派到Item
本身,擺脫所有的item.xxx
符號。
struct Item {
int weight;
int cost;
void algo( int& cost_low, int& cost_high, int& throw_weight ) {
int quantity = throw_weight / weight;
int remainder = throw_weight % weight;
cost_low=(quantity-1)*cost;
cost_high=quantity*cost;
throw_weight -= (quantity-1)*weight;
if( remainder != 0 ) {
cost_low += cost;
cost_high += cost;
throw_weight += weight;
}
}
};
用法:
item_matrix[item_id].algo( cost_low, cost_high, throw_weight );
只需將枚舉數定義為0和1:
enum item_type
{
weight = 0
, cost = 1
};
從enum
到int
的標准轉換將允許您使用枚舉為數組建立索引。
如果我正確理解了您的問題,那么我認為您想將enum
用作數組的索引。 如果是這樣,那么您可以這樣做:
quantity=throw_weight/item_matrix[item_id][weight]; //weight <=> 0
cost_low=(quantity-1)*item_matrix[item_id][cost]; //cost <=> 1
weight
和cost
的值分別為0
和1
,因此上面的代碼非常合適。 如果未提供枚舉值,則該值將從0
開始,並在每個后續枚舉標簽處遞增1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.