Tuesday, June 7, 2016

[C++] String Stream

#include #include 
using namespace std; /* * */ 
int main(int argc, char** argv) 
 stringstream ss ; 
 int x, y, value; 
 ss << "123 456 789"; 
 ss >> x >> y >> value; 
 cout << "X:" << x << " Y:" << y << " Value:" << value << endl; 
 return 0; 
}

[C++] Clone

class Test { private: blah blah; public: blah blah blah; Test* Clone() const { return new Test(*this); } } // Caution : Maybe, deep copy is necessary if there is/are pointer variable(s)

[C++] Custom sort

----------------- test.h --------------------#ifndef _TEST_H_ #define _TEST_H_ #include using namespace std; class XY { private: int _x, _y, _value; public: XY() {}; XY(int x, int y, int value) { _x = x; _y = y; _value = value; } ~XY() {} int X() const { return _x; } int Y() const { return _y; } int value() const { return _value; } void SetValues(int x, int y, int value) { _x = x; _y = y; _value = value; } // < operator overloading // x-coordination has first priority, then y-coordingation bool operator<(const XY &xy) const; friend const ostream& operator<<(ostream &os, const XY &xy); }; #endif ------------------- test.cpp ---------------------- #include "test.h" using namespace std; bool XY :: operator<(const XY &xy) const { if( _x < xy.X() ) return true; else if( _x == xy.X() ) { if( _y < xy.Y() ) return true; else return false; } return false; } const ostream& operator<<(ostream &os, const XY &xy) { os << "(" << xy._x << "," << xy._y << ") -> " << xy._value ; return os; } ----------------------- main.cpp -------------------------- #include "test.h" #include #include using namespace std; int main() { vector vec_xy; XY t; t.SetValues(1,1,1); vec_xy.push_back(t); t.SetValues(2,2,4); vec_xy.push_back(t); t.SetValues(1,2,3); vec_xy.push_back(t); t.SetValues(2,1,3); vec_xy.push_back(t); for( int i = 0 ; i < vec_xy.size() ; i++ ) { cout << vec_xy[i] << endl; } cout << "---------- sort -------------" << endl; sort(vec_xy.begin(), vec_xy.end()); for( int i = 0 ; i < vec_xy.size() ; i++ ) { cout << vec_xy[i] << endl; } }

[C++] Re-direction cout to log file

#include #include using namespace std; ofstream _log_file_; ... ... ... _log_file_.open("log.txt"); if( !_log_file_.is_open() ) { // Error handling } _log_file_.copyfmt( cout ); cout.rdbuf( _log_file_.rdbuf() ); // From now on, text of cout re-direct to file : log.txt ... ... ... _log_file_.close();

Thursday, June 2, 2016

[C++] For Loop (C++ 11)

Range Based for loop double values[5] = {1.1, 2.2, 3.3, 4.4, 5,5}; for (double x : values) { cout << x << endl; } // when I want to change the value of elements for (double &x : values) { x *= 0.9; } for (int x : {1, 2, 3}) { cout << x << endl; }