#include <iostream>
using namespace std;
class Vector {
public:
float x, y, z;
Vector(float x, float y, float z)
: x(x), y(y), z(z) {
}
float operator[](int idx) const {
if (idx < 1)
return x;
if (idx == 1)
return y;
return z;
}
// 첨자는 외부에서 수정을 하려면 함수를 2개 만들어야한다.
float& operator[](int idx) {
if (idx < 1)
return x;
if (idx == 1)
return y;
return z;
}
};
int main() {
Vector v{ 1, 2, 3 };
cout << v[-1] << endl;
cout << v[0] << endl;
cout << v[1] << endl;
cout << v[2] << endl;
cout << v[3] << endl;
v[1] = 100;
cout << v[1] << endl;
}
1
1
2
3
3
100
#include <iostream>
#include <cstring>
using namespace std;
class String {
private:
char* _chars;
public:
String(const char* chars)
: _chars(new char[strlen(chars) + 1]) {
strcpy(_chars, chars);
}
char operator[](int idx) const {
return _chars[idx];
}
char& operator[](int idx) {
return _chars[idx];
}
friend ostream& operator<<(ostream& os, const String& s) {
os << s._chars;
return os;
}
};
int main() {
String s("abc");
cout << s[0] << endl;
s[0] = 'b';
s[2] = 'q';
cout << s << endl;
}
a
bbq
#include <iostream>
#include <vector>
using namespace std;
using Key = string;
using Value = string;
using KeyValue = pair<string, string>;
class Bucket {
private:
vector<KeyValue> _items;
public:
Value& get(const Key& key) {
for (KeyValue& keyValue : _items) {
if (keyValue.first == key) {
return keyValue.second;
}
}
_items.push_back(std::make_pair(key, Value()));
return _items.back().second;
}
};
class HashTable {
private:
vector<Bucket> _buckets;
// 원형 : vector<vector<pair<string, string>>> _buckets;
int hash(const Key& key) const {
int h = 0;
for (char ch : key)
h += ch;
return h;
}
public:
HashTable(int size = 100)
: _buckets(vector<Bucket>(size)) {
}
Value& operator[](Key key) {
int bucketidx = hash(key) % _buckets.size();
Bucket& bucket = _buckets[bucketidx];
return bucket.get(key);
}
};
int main() {
HashTable hashTable;
hashTable["abc"] = "def";
hashTable["qwe"] = "qqq";
hashTable["ewq"] = "eee";
cout << hashTable["abc"] << endl;
cout << hashTable["qwe"] << endl;
cout << hashTable["ewq"] << endl;
}
def
qqq
eee