https://github.com/wuye9036/CppTemplateTutorial
chap1 无他, 唯手熟尔
Reading notes: till 2.3 即用即推导 (2018.05.29)
Tuesday, 29 May 2018
Thursday, 24 May 2018
Implement Case Insensitive string by overwriting C++ basic_string template traits parameter
include<string>
#include<iostream>
using namespace std;
class CaseInsensitiveTraits: public std::char_traits<char> {
public:
static bool lt (char one, char two) {
return std::tolower(one) < std::tolower(two);
}
static bool eq (char one, char two) {
return std::tolower(one) == std::tolower(two);
}
static int compare (const char* one, const char* two, size_t length) {
for (size_t i = 0; i < length; ++i) {
if (lt(one[i], two[i])) return -1;
if (lt(two[i], one[i])) return +1;
}
return 0;
}
};
typedef basic_string<char, CaseInsensitiveTraits> cistring;
int main(void) {
cistring c1 = "HI!", c2 = "hi!";
if (c1 == c2) { // Always true
cout << "Strings are equal." << endl;
}
cout << "c1 length is " << c1.size() << endl;
cout << "Find 'I' in c1 length: " << c1.find('I') << endl;
cout << "Find 'h' in c1 length: " << (int) c1.find('h') << endl;
}
#include<iostream>
using namespace std;
class CaseInsensitiveTraits: public std::char_traits<char> {
public:
static bool lt (char one, char two) {
return std::tolower(one) < std::tolower(two);
}
static bool eq (char one, char two) {
return std::tolower(one) == std::tolower(two);
}
static int compare (const char* one, const char* two, size_t length) {
for (size_t i = 0; i < length; ++i) {
if (lt(one[i], two[i])) return -1;
if (lt(two[i], one[i])) return +1;
}
return 0;
}
};
typedef basic_string<char, CaseInsensitiveTraits> cistring;
int main(void) {
cistring c1 = "HI!", c2 = "hi!";
if (c1 == c2) { // Always true
cout << "Strings are equal." << endl;
}
cout << "c1 length is " << c1.size() << endl;
cout << "Find 'I' in c1 length: " << c1.find('I') << endl;
cout << "Find 'h' in c1 length: " << (int) c1.find('h') << endl;
}
Subscribe to:
Posts (Atom)