Created
March 15, 2012 23:47
-
-
Save Kedrigern/2047716 to your computer and use it in GitHub Desktop.
C++: Basic example of template and std libs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <string> | |
#include <iostream> | |
#include <algorithm> | |
using namespace std; | |
template <typename T> | |
void print(T element) { | |
cout << element << ' '; | |
} | |
int main() { | |
vector< char > v(5,'b'); // ={'b','b','b','b','b'}; | |
string s("ccccc"); | |
vector< char > v2 = v; | |
v.push_back('2'); | |
cout << "Posledni prvek z v2:\t" << v2[ v2.size()-1 ] << endl; // out: b | |
for_each(v.begin(), v.end(), print<char>); // out: b b b b b 2 | |
cout << endl; | |
} | |
struct hover { | |
int priority; | |
char pismeno; | |
hover(char pis, int pr) { | |
pismeno = pis; | |
priority = pr; | |
} | |
bool operator< (const hover& druhy) const { | |
return priority < druhy.priority; | |
} | |
}; | |
struct lessHover { | |
bool operator() (const hover& prvni, const hover& druhy) const { | |
return prvni.priority < druhy.priority; | |
} | |
}; | |
struct greaterHover { | |
bool operator() (const hover& prvni, const hover& druhy) const { | |
return prvni.priority > druhy.priority; | |
} | |
}; | |
template<typename T> | |
void print(T element) { | |
cout << element << ' '; | |
} | |
template<> | |
void print<hover>(hover element) { | |
cout << element.pismeno << ' '; | |
} | |
int main() | |
{ | |
hover h1('a',1); | |
hover h2('b',2); | |
hover h3('w',0); | |
if( h1 < h2 ) { cout << "true" << endl;} // out: true | |
set< hover, lessHover > mn; | |
mn.insert( h1 ); | |
mn.insert( h2 ); | |
mn.insert( h3 ); | |
for_each( mn.begin() , mn.end(), print<hover> ); | |
cout << endl; // out: w a b | |
set< hover, greaterHover > mn2; | |
mn2.insert( h1 ); | |
mn2.insert( h2 ); | |
mn2.insert( h3 ); | |
for_each( mn2.begin() , mn2.end(), print<hover> ); | |
cout << endl; // out: b a w | |
priority_queue<hover,vector<hover>,lessHover> fronta; | |
fronta.push(h1); | |
fronta.push(h2); | |
fronta.push(h3); | |
while( ! fronta.empty() ) { | |
cout << fronta.top().pismeno << ' '; | |
fronta.pop(); | |
} // out: b a w | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment