我有一個問題,一直困擾着我一段時間&我還沒有想出一個解決方案。我想創建一個容器類來存儲對象&根據它們的一個成員變量值對它們進行排序。因此,如果我有一班學生(使用成員變量int studentID),我想根據他們的studentID值按升序將它們存儲在我的Container類中。我已經將容器類作爲模板類,以便我可以在任何項目中使用任何類。存儲一個指向對象成員變量的指針
我的容器類問題:我無法存儲對象的指針(例如學生對象)。更準確的問題是我無法將引用(?)存儲到對象成員變量(例如,引用/指向學生的studentID變量的指針)。
這個問題一直令我很煩,我年齡&任何信息或建議將不勝感激。有沒有辦法讓我的下面的Container類存儲指針對象成員變量?有沒有不同的方法來創建一個可以通過它們的成員變量排序的對象的容器?
#include <iostream>
using namespace std;
template <typename Object, typename dataType>
class Collection
{
public:
Collection(dataType Object::*nMemberVariable)
{
memberVariable = nMemberVariable;
}
bool store(Object* o)
{
// check that o is not a NULL pointer & not already present in maps
if (o==NULL || instanceVarMap.find(o->*memberVariable) != instanceVarMap.end())
{
return false;
}
instanceVarMap.insert(o->*memberVariable, o);
return true;
}
private:
dataType Object::* memberVariable;
std::map <dataType, Object*> instanceVarMap;
};
struct FoodItem
{
unsigned int ID;
string name;
double price;
};
int main()
{
// I am attempting to store a pointer to an objects member variable
// this is so I can create a custom container class(like a map or vector) that
// sorts its contents (which are FoodItem objects) according to their member variable values
// so a container could sort all its elements according to a FoodItems ID value or name value
Collection <FoodItem*> foodCol(&FoodItem::name);
string nNames[] = {"a", "b", "c", "d"};
double nPrices[] = {1.1, 2.2, 3.3, 4.4};
for (int i=0; i<4; i++)
{
FoodItem *f = new FoodItem() { i, nNames[i], nPrices[i] };
foodCol.store(f);
}
// Note storing an ACTUAL object is possible with this class
Collection <FoodItem*> foodCol(&FoodItem::name);
FoodItem f(1, "a", 4);
foodCol.store(f);
system("PAUSE");
return 0;
}