好吧,我的指针技术有点差。我正在创建自己的简单 map 容器,可以在其中存储不同的数据类型。我正在尝试创建 insertPair()
方法,其中一个结构存储在一个指针数组中,但我正在努力解决语法问题。我创建了一个结构,我试图将 a
的值分配给 temp.key
并将 b
的值分配给 temp.value
。我该怎么做并将结构存储在指针数组中?我在 main()
中创建了一个 test
对象,并传入了一个 int
和一个 string
。非常感谢任何指导。谢谢
template <typename K, typename V>
class CMyMap
{
int arraysize;
CMyMap* myArr[5];
public:
struct pair
{
K key;
V value;
};
CMyMap()
{
arraysize = 0;
}
void insertPair(K a, V b)
{
pair* temp = new pair;
temp->key = a;
temp->value = b;
myArr[0] = temp; // trying to store the values of temp.key and temp.value to myArr[0]
}
void display()
{
// dont how to display the key and value correctly.
cout << myArr[0] << endl;
}
};
int main()
{
CMyMap<int, string> test;
test.insertPair(23, "bob");
test.display();
cin.get();
}
最佳答案
temp.key = a;
应该是 temp->key = a;
。
同样,temp.value
应该是temp->value
。
要获取或设置 *myArr
中索引 i
处的值,您将使用 (*myArr)[i]
,因为 myArr
是一个指向数组的指针。
关于c++ - 如何使用模板将结构存储在指针数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26685353/