我的任务是编写字典之类的东西,我为含义分配内存的方式只是在构造函数中分配 100 个含义,效果非常好。
然而,教授不同意,他让我重写代码,让我为相关数量的含义分配内存。我基本上不知道该怎么做,构造函数如何提前知道我会有多少含义?
你们有什么建议?我只发布了与问题相关的部分代码。
#include"expression.h"
//---------------------METHODS-------------------------------------------
Expression::Expression(int m_ctr)
{
count_meanings = m_ctr; // Set the counter to 0
meanings = new char * [100]; // Allocate memory for 100 meanings
}
Expression::~Expression()
{
delete [] meanings; // Free the allocated memory
delete [] word_with_several_meanings; // Free the allocated memory
}
void Expression::word(char *p2c)
{
word_with_several_meanings = new char[strlen(p2c)+1];
strcpy(word_with_several_meanings, p2c); // copy the string, method: DEEP copy
}
void Expression::add_meaning(char *p2c)
{
meanings[count_meanings] = new char[strlen(p2c)+1];
strcpy(meanings[count_meanings++], p2c); // copy the string, method: DEEP copy
}
char * Expression::get_word()
{
return word_with_several_meanings;
}
char * Expression::get_meaning(int n_meaning)
{
return * (meanings + n_meaning);
}
int Expression::get_total_number_of_meanings()
{
return count_meanings;
}
int main(void)
{
Expression expr;
expr.word("bank");
expr.add_meaning("a place to get money from");
expr.add_meaning("a place to sit");
cout << expr.get_word() << endl;
for(int i = 0; i<expr.get_total_number_of_meanings(); i++)
cout << " " << expr.get_meaning(i) << endl;
最佳答案
C++ 方法是使用:
-
std::string
存储单个字符串(而不是原始的 char* C 类字符串) -
std::vector
存储一系列字符串(如字典中的“含义”)
所以,你可以有一个vector<string>
类中的数据成员,您可以使用 string
为其动态添加含义(即 vector::push_back()
s) .
如果您出于某种原因想要留在原始 C 级别,您可以使用 linked list数据结构,在每个节点内部存储一个原始的 C 字符串指针,当你添加一个新的含义时,你可以创建一个指向该字符串的新节点,并将该节点添加到链表中。具有这样的节点定义的单链表可能就足够了:
struct MeaningListNode
{
char * Meaning; // Meaning raw C string
struct MeaningListNode* Next; // Pointer to next meaning node, or nullptr for last
};
但是,坦率地说,vector<string>>
对我来说,这种方法似乎更简单、更好。
关于c++ - 如何为特定数量的字符串分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22967676/