码迷,mamicode.com
首页 > 其他好文 > 详细

简单模拟STL库中string的实现

时间:2016-03-11 22:32:35      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:简单模拟stl库中string的实现


#include<iostream>
#include<assert.h>
#include<malloc.h>
#define CAPACITY 3
using namespace std;

class String
{
public:
	String(char *str="")
		:_str((char*)malloc(strlen(str)+1)),
	     _size(strlen(str))
	{
		strcpy(_str, str);
		_capacity = _size+1;
		cout << "构造函数" << endl;
	}
	String(String  const&objstr)
		:_str(NULL),
		_size(objstr._size),
		_capacity(objstr._capacity)
	{
		String tmp(objstr._str);
		swap(_str, tmp._str);
	}
	~String()
	{
		cout << "析构函数" << endl;
		if (_str)
		{
			free(_str);
		}
		
	}
	size_t newcapacity(size_t size)
	{
		if (size > _capacity)
		{
			
			_str = (char*)realloc(_str, (size + CAPACITY));
		
		}
		return size + CAPACITY;
	}
	void display()
	{
		cout << _str << endl;
	}
	void Pushback(char str)
	{
		int size = _capacity+1;
		_capacity = newcapacity(size);
		_str[_size] = str;
		_str[_size + 1] = ‘\0‘;
		_size = _size + 1;
	}
	int Find(char x)
	{
		if (_str == NULL)
		{
			return -1;
		}
		int i = 0;
		for (; i <= (int)_size; i++)
		{
			if (_str[i] == x)
			{
				return i;
			}
		}
		return -1;
	}
	void insert(char x, size_t pos)
	{
		int size = _size + 1;
		_capacity = newcapacity(size);
		int i = _size;
		for (; i >(int)pos; i--)
		{
			_str[i+1] = _str[i];
		}
		_str[pos+1] = x;
		_size = _size + 1;
	}
	String &operator =(String const &str)
	{
		if (str._str == NULL)
		{
			_str = NULL;
			_size = str._size;
     		return *this;
		}
		_capacity = newcapacity(str._capacity);
		char *str1 = str._str;

		strcpy(_str, str1);
		_size = str._size;
		return *this;
	}
	int &operator>(String const &str)
	{
		int ret = strcmp(_str, str._str);
		return ret;
	}
private:
	char * _str;
	size_t _size;
	size_t _capacity;
};

void Test1()
{
	String str1("abcdef");
	String str2(str1);
	int ret=str2.Find(‘d‘);
	str2.insert(‘x‘, ret);
	str2.Pushback(‘a‘);
	cout << ret << endl;
	str2.display();
}

void Test2()
{
	String s1("abcdef");
	String s2("efghlmn");
	s1 = s2;
	s1.display();
}

int main()
{
	//Test1();
	Test2();
	return 0;
}


本文出自 “痕迹” 博客,请务必保留此出处http://wpfbcr.blog.51cto.com/10696766/1750081

简单模拟STL库中string的实现

标签:简单模拟stl库中string的实现

原文地址:http://wpfbcr.blog.51cto.com/10696766/1750081

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!