模拟string
namespace lld
{
class string
{
public :
typedef char * iterator;
typedef const char * const_iterator;
iterator begin ( )
{
return _str;
}
iterator end ( )
{
return _str + _size;
}
const_iterator begin ( ) const
{
return _str;
}
const_iterator end ( ) const
{
return _str + _size;
}
string ( const char * str = "" )
: _size ( strlen ( str) )
{
_capacity = _size;
_str = new char [ _capacity + 1 ] ;
strcpy ( _str, str) ;
}
string ( const string& s)
: _size ( s. _size)
, _capacity ( s. _capacity)
{
_str = new char [ _capacity + 1 ] ;
strcpy ( _str, s. _str) ;
}
string& operator = ( const string& s)
{
if ( this != & s)
{
char * tmp = new char [ s. _capacity + 1 ] ;
strcpy ( tmp, s. _str) ;
delete [ ] _str;
_str = tmp;
_size = s. _size;
_capacity = s. _capacity;
}
return * this ;
}
~ string ( )
{
delete [ ] _str;
_str = nullptr ;
_size = _capacity = 0 ;
}
char & operator [ ] ( size_t pos)
{
assert ( pos < _size) ;
return _str[ pos] ;
}
const char & operator [ ] ( size_t pos) const
{
assert ( pos < _size) ;
return _str[ pos] ;
}
size_t size ( ) const
{
return _size;
}
bool operator > ( const string& s) const
{
return strcmp ( _str, s. _str) > 0 ;
}
bool operator == ( const string& s) const
{
return strcmp ( _str, s. _str) == 0 ;
}
bool operator >= ( const string& s) const
{
return * this > s || * this == s;
}
bool operator < ( const string& s) const
{
return ! ( * this >= s) ;
}
bool operator <= ( const string& s) const
{
return ! ( * this > s) ;
}
bool operator != ( const string& s) const
{
return ! ( * this == s) ;
}
private :
char * _str;
size_t _size;
size_t _capacity;
} ;
}