gpt4 book ai didi

c++ - 存储指向对象成员变量的指针

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:34:58 26 4
gpt4 key购买 nike

我有一个问题困扰了我一段时间,而且我还没有想出解决方案。我想创建一个容器类来存储对象并根据它们的一个成员变量值对它们进行排序。因此,如果我有一个 Students 类(成员变量为 int studentID),我想根据他们的 studentID 值按升序将它们存储在我的 Container 类中。我已将容器类设为模板化类,这样我就可以在我的任何项目中使用任何类。

我的 Container 类的问题: 我无法存储对象的指针(例如 Student 对象)。更准确地说,问题是我无法存储对对象成员变量的引用(?)(例如,对学生的 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;
}

最佳答案

如果我理解正确的话,你问的似乎是一个集合std::set 可以将用于排序的谓词作为第二个模板参数。如果您准备一个比较目标成员进行排序的谓词,set 中的元素将根据该成员进行排序。
例如:

#include <set>

struct FoodItem {
unsigned int ID;
double price;
};

template< class C, class T, T C::* M >
struct member_comparator { // predicate
bool operator()( C const* x, C const* y ) const { return x->*M < y->*M; }
};

int main() {
FoodItem a = { 1, 2.5 }, b = { 2, 1.5 };
// a set sorted by ID
std::set< FoodItem*
, member_comparator< FoodItem, unsigned, &FoodItem::ID > > s_ID;
s_ID.insert( &a );
s_ID.insert( &b );
// a set sorted by price
std::set< FoodItem*
, member_comparator< FoodItem, double, &FoodItem::price > > s_price;
s_price.insert( &a );
s_price.insert( &b );
}

这是对 ideone 的测试.

关于c++ - 存储指向对象成员变量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6234040/

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