gpt4 book ai didi

c++ - 节点插入cpp

转载 作者:行者123 更新时间:2023-11-28 05:29:57 25 4
gpt4 key购买 nike

如何在一个函数中编写这 3 个成员函数定义?如果可能的话。你能解释一下你是怎么做到的吗?抱歉,我英语不好,也不擅长编码,请不要侮辱我。

 void insert(int idx, PW* obj) 
{
idx--;
double bd = summaryCost();
node x(1);
x.p = obj;

if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}

void insert(int idx, FW* obj) {
idx--;
double bd = summaryCost();
node x(2);
x.f = obj;
if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}

void insert(int idx, TW* obj) {
idx--;
double bd = summaryCost();
node x(3);
x.t = obj;
if (bd + obj->getCost() <= budget) {
if (idx <= vec.size()) {
vec.insert(vec.begin() + idx, x);
remain -= obj->getCost();
} else {
delete obj;
throw IndexOut();
}
} else {
delete obj;
throw DeficitError();
}
}

最佳答案

如果 PWFWTW 没有公共(public)基类,您可以使用特征类和模板。

完整示例:

// Empty types for illustration purposes.
struct PW {};
struct FW {};
struct TW {};

struct node
{
node(int i) {}
PW* p;
FW* f;
TW* t;
};

// For readability improvement.
template<typename T>
using member_ptr = T* node::*;

template<typename T>
struct NodeTraits {};

// Class-specific traits
template<>
struct NodeTraits<PW> {
enum {value = 1};
static member_ptr<PW> member;
};

template<>
struct NodeTraits<FW> {
enum {value = 2};
static member_ptr<FW> member;
};

template<>
struct NodeTraits<TW> {
enum {value = 3};
static member_ptr<TW> member;
};

member_ptr<PW> NodeTraits<PW>::member = &node::p;
member_ptr<FW> NodeTraits<FW>::member = &node::f;
member_ptr<TW> NodeTraits<TW>::member = &node::t;

// Finally, the function...
template<typename T>
void insert(int idx, T* obj)
{
node x(NodeTraits<T>::value);
member_ptr<T> ptr = NodeTraits<T>::member;
x.*ptr = obj;
// ...
}

// Using it...
int main()
{
PW p;
FW f;
TW t;
insert(0, &p);
insert(0, &f);
insert(0, &t);
}

留给感兴趣的读者的解释作为练习。

关于c++ - 节点插入cpp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39770882/

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