如何为特定数量的字符串分配内存
How to allocate memory for specific number of strings?
我被赋予了编写字典之类的程序的任务,而我为含义分配内存的方式只是在构造函数中分配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
存储单个字符串(而不是原始字符*C类字符串)std::vector
存储字符串序列(如字典中的"含义")
因此,您可以在类中有一个vector<string>
数据成员,并且可以使用vector::push_back()
为其动态添加含义(即string
s)。
如果出于某种原因想要保持原始C级别,可以使用链表数据结构,在每个节点内存储一个原始C字符串指针,当添加新含义时,可以创建一个指向该字符串的新节点,并将该节点添加到链表中。有这样一个节点定义的单链表可能就足够了:
struct MeaningListNode
{
char * Meaning; // Meaning raw C string
struct MeaningListNode* Next; // Pointer to next meaning node, or nullptr for last
};
但是,坦率地说,vector<string>>
方法对我来说似乎更简单、更好。
相关文章:
- 我如何通过引用将 c++ 字符串分配给另一个字符串
- 无法在 c++ 中将字符串分配给字符串数据类型
- 将字符串* 分配给字符* c++
- 如何为C++字符串分配空指针参数?
- 为什么在构造函数中将字符串分配给指针是安全的?
- 如何将wchar_t字符串分配给用户定义类的 CString 成员
- 字符串分配
- 如何将字符串分配给向量(均在堆上)
- 确实为其写入的字符串分配内存
- 简单的字符串分配导致分割故障
- 通过新行不使用字符串流将C 字符串分配
- 将字符串分配到动态数组位置时出错
- 在 c++ 中为字符串分配其分配的大小值是否正确
- 从被空间分开的字符串分配给变量?C [QT]
- 将字符串分配给固定长度的字符数组
- 将一组字符串分配给向量c++的内容
- 如何为字符串分配内存
- C++中的字符串分配:为什么这样做
- 视觉 建议在C++中执行字符串分配什么?
- 字符 *str;str= "HELLO" ;如何在不为字符串分配任何内存的情况下工作?