我应该创建一个具有以下行为的成员函数: 无效grow()
我不确定如何动态地将data_分配为大小2以及第二个项目符号。这让我很困惑。
#pragma once
#include<iostream>
using std::cout; using std::endl; using std::boolalpha; using std::ostream;
#include<initializer_list>
using std::initializer_list;
#include <algorithm>
using std::max; using std::copy; using std::swap;
#include <utility>
using std::make_pair; using std::pair;
#include <stdexcept>
using std::runtime_error;
#include<vector>
using std::vector;
const static size_t element_array_size = 5;
template<typename K, typename V>
struct Element{
public:
K key_;
V values_[element_array_size];//capacity of values
size_t count_ = 0; //number of values filling values_
Element()=default;
Element(K, initializer_list<V>);
bool operator==(const Element&)const;
bool operator<(const K&) const;
friend ostream& operator<<(ostream& os, const Element& ele){//output element ele
os<<ele.key_<<":";//display key
std::copy(ele.values_,(ele.values_+ele.count_-1),std::ostream_iterator<V>(os,","));//display values
os<<ele.values_[ele.count_-1];
return os;
};//of friend function
};
//count_ and num_keys_ should never be greater than the size or num_elements_
//Code for Element functions goes here
template<typename K, typename V>
class MVM{
public:
Element<K, V> *data_ = nullptr;
size_t num_keys_ = 0;
size_t num_elements_ = 0; //capacity
Element<K, V> *find_key(K);
size_t find_value(V, K*&);
void grow();
public:
MVM()=default;
MVM(initializer_list<Element<K,V>>);
MVM(const MVM&);
~MVM() {delete[] data_;}
size_t size();
bool add(K,V);
bool remove_key(K);
size_t remove_value(V, K*&);
friend ostream& operator<<(ostream& oss, const MVM& mv){
//Code for the ostream operator goes here
std::copy(mv.data_,(mv.data_+mv.num_keys_-1),std::ostream_iterator<Element<K,V>>(oss," "));//copy elements with spaces in between to ostream oss
oss<<mv.data_[mv.num_keys_-1];
return oss;
}//of friend function
};
...
答案 0 :(得分:0)
如果使用矢量,则可以使用以下方法创建更大的矢量:
vector<string> Wibble;
Wibble.resize(10);
...
// or:
...
Wibble.push_back("hello");
Wibble.push_back("world");
或者,如果您使用的是C,则可以走malloc路由,只要您记得以后可以释放它即可:
char *Data=(char *)malloc(10*sizeof(char));
...
Data=(char *)realloc(Data,20*sizeof(char));
...
free(Data);
您不能做的是将一些静态大小的东西夹在堆栈上,然后改变主意:
char Data[10];
尺寸始终为10,任何尝试更改尺寸都会给您带来麻烦。