【发布时间】:2021-09-05 06:15:09
【问题描述】:
我创建了一个类Vector,其中包含两个作为模板变量的变量,我正在尝试构建这样一个字典来告诉特定学生的标记。
问题是我正在努力使用模板动态分配内存。我必须这样做没有地图或 STL 帮助。你能解释一下,如何正确分配它们。
#define DEF_CAPACITY 20
template <class U, class T>
class Vector {
protected:
T* _data;
U* _keys;
int _size; //size in use
int _capacity; //available capacity
public:
//constructors
Vector(int capacity = DEF_CAPACITY);
~Vector();
int getSize() const { return size; }
void insert(U key, T data);
T operator[](U key);
};
template<class U, class T>
inline Vector<U, T>::Vector(int capacity)
{
this->_capacity = capacity;
this->_size = 0;
}
template<class U, class T>
Vector<U, T>::~Vector()
{
if (_data)
delete[] _data;
if (_keys)
delete[] _keys;
}
template<class U, class T>
void Vector<U, T>::insert(U key, T data)
{
_keys[_size] = new U;
//Maybe I have to do something like that, but all options I test doesn't work
//keys[_size] = new U[Some size];
_keys[_size] = key;
_data[_size] = new T;
_data[_size] = data;
_size++;
}
template<class U, class T>
T Vector<U, T>::operator[](U key)
{
int index = 0;
for (int i = 0; i < size; i++)
if (_keys[i] == key)
index = i;
return _data[index];
}
int main() {
Vector<string, int> grades;
grades.insert("john", 90);
grades.insert("marc", 100);
grades.insert("ron", 87);
grades.insert("lynda", 95);
//...
grades.insert("Tome", 93);
//...
cout << grades["marc"] << endl;
cout << grades["lynda"] << endl;
cout << grades["john"] << endl;
return 0;
}
【问题讨论】:
-
std::vector<std::pair<Key, Value>>或std::map<Key, Value>怎么样? -
@Jarod42 如果你有一个可以在没有 STL 帮助的情况下解决问题的解决方案
-
如果你不能使用 std(使用
std::string时这似乎很奇怪),创建你自己的 Vector 和 Pair 类(或你的二叉树)。 -
这是一个分配的项目吗?因为
std::map<std::string, int>就是答案。
标签: c++ templates dynamic dynamic-memory-allocation