手写基本的String类

String类是C++模板库中的一个方法类,书写其基本方法是考验C++初学者一个很经典的考题,如果注意细节、写的完美的话也不是那么容易的,写个博客加强一下记忆。

 

//基本String类方法
class String
{
public :
	String(const char* str = NULL);
	String(const String &other);
	~String();
	String &operator=(const String& rhs);
	void Show();
private:
	char* m_data;
};
//方法实现:
String::String(const char* str)
{
	if (str == NULL)
	{
		m_data = new char[1];
		m_data = '\0';
	}
	else
	{
		int num = strlen(str);
		m_data = new char[num+1];
		strcpy(m_data, str);
	}
	cout << this <<"构造!" << endl;
}
String::~String()
{
	delete[] m_data;
	m_data = NULL;
	cout << this <<"析构" << endl;
}

String::String(const String& other)
{
	int len = strlen(other.m_data);
	m_data = new char[len+1];
	strcpy(m_data, other.m_data);
	cout &
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的基于链表实现的手写Map示例,你可以参考一下: ```c++ #include <iostream> #include <string> using namespace std; template <typename KeyType, typename ValueType> class Map { private: struct Node { KeyType key; ValueType value; Node* next; Node(const KeyType& k, const ValueType& v) : key(k), value(v), next(nullptr) {} }; Node* head; public: Map() : head(nullptr) {} ~Map() { Node* node = head; while (node != nullptr) { Node* next = node->next; delete node; node = next; } } void insert(const KeyType& k, const ValueType& v) { Node* node = head; while (node != nullptr) { if (node->key == k) { node->value = v; return; } node = node->next; } node = new Node(k, v); node->next = head; head = node; } const ValueType& operator[](const KeyType& k) const { Node* node = head; while (node != nullptr) { if (node->key == k) { return node->value; } node = node->next; } throw "Key not found!"; } bool contains(const KeyType& k) const { Node* node = head; while (node != nullptr) { if (node->key == k) { return true; } node = node->next; } return false; } }; int main() { Map<string, int> myMap; myMap.insert("apple", 3); myMap.insert("banana", 6); myMap.insert("cherry", 9); cout << myMap["apple"] << endl; // 3 cout << myMap["banana"] << endl; // 6 cout << myMap["cherry"] << endl; // 9 cout << myMap["durian"] << endl; // throws "Key not found!" if (myMap.contains("apple")) { cout << "myMap contains 'apple'" << endl; } if (!myMap.contains("durian")) { cout << "myMap does not contain 'durian'" << endl; } return 0; } ``` 在这个示例中,我们使用了一个简单的单向链表来存储键值对。Map提供了三个基本的操作:insert、operator[]和contains。insert操作将一个键值对插入到链表中,如果键已经存在,则更新对应的值。operator[]操作用于获取特定键的值,如果键不存在,则抛出异常。contains操作用于检查特定键是否存在于Map中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值