最近为了面试,在自写一些常用数据结构。目前打算写的包括BST,list,string,heap,并查集,Trie树。
string类模板
#include<iostream>
#include<ostream>
#pragma warning disable:4996
using namespace std;
class mystring {
private:
char* data;
int size;
public:
mystring() {
data = new char[1];
data[0] = '\0';
size = 0;
}
~mystring() {
delete[]data;
}
mystring(const mystring& str) {
size = str.size;
data = new char[size + 1];
strcpy(data, str.data);
}
mystring(const char* str) {
size = strlen(str);
data = new char[size + 1];
strcpy(data, str);
}
mystring& operator=(const mystring& str) {
if (&str == this) {
return *this;
}
delete data;
size = str.size;
data = new char[size + 1];
strcpy(data, str.data);
return *this;
}
mystring& operator=(const char* str) {
delete[]data;
size = strlen(str);
data = new char[size + 1];
strcpy(data, str);
return *this;
}
char& operator[](int i) {
return data[i];
}
const char& operator[](int i)const {
return data[i];
}
bool operator<(mystring& str) {
return (strcmp(data, str.data) < 0);
}
bool operator>(mystring& str) {
return str < *this;
}
bool operator==(mystring& str) {
return strcmp(data, str.data) == 0;
}
friend ostream& operator<<(ostream& os, const mystring& st) {
os << st.data;
return os;
}
friend istream& operator >> (istream& is, mystring& st) {
char tmp[100];
is.get(tmp, 100);
if (is)
st = tmp;
while (is&&is.get() != '\n')
continue;
return is;
}
};
int main() {
char* s1 = "abcdefg";
mystring mystr2 = "ddddddd";
mystring mystr(s1);
bool a = mystr < mystr2;
cout << "mystr<mystr2 " << a << endl;
cout << mystr<<endl;
mystr = mystr2;
cout << mystr << endl;
bool b = mystr == mystr2;
cout << "mystr==mystr2 " << b << endl;
return 0;
}