C++


All_Header

  1. #pragma once
  2.  
  3. #define _USE_MATH_DEFINES
  4.  
  5. #include <complex>
  6. #include <exception>
  7. #include <fstream>
  8. #include <iomanip>
  9. #include <ios>
  10. #include <iosfwd>
  11. #include <iostream>
  12. #include <istream>
  13. #include <limits>
  14. #include <locale>
  15. #include <memory>
  16. #include <new>
  17. #include <ostream>
  18. #include <sstream>
  19. #include <stdexcept>
  20. #include <streambuf>
  21. #include <string>
  22. #include <typeinfo>
  23. #include <valarray>
  24. #include <algorithm>
  25. #include <bitset>
  26. #include <deque>
  27. #include <functional>
  28. #include <iterator>
  29. #include <list>
  30. #include <map>
  31. #include <numeric>
  32. #include <queue>
  33. #include <set>
  34. #include <stack>
  35. #include <utility>
  36. #include <vector>
  37. #include <cassert>
  38. #include <cctype>
  39. #include <cerrno>
  40. #include <cfloat>
  41. #include <ciso646>
  42. #include <climits>
  43. #include <clocale>
  44. #include <cmath>
  45. #include <csetjmp>
  46. #include <csignal>
  47. #include <cstdarg>
  48. #include <cstddef>
  49. #include <cstdio>
  50. #include <cstdlib>
  51. #include <cstring>
  52. #include <ctime>
  53. #include <cwchar>
  54. #include <cwctype>
  55.  
  56. #ifdef _MSC_VER
  57. #include <windows.h>
  58. #endif
  59.  
  60. #ifdef _MSC_VER
  61. #define SLEEP(x) Sleep(1000*x)
  62. #else
  63. #define SLEEP(x) sleep(x)
  64. #endif
  65.  
  66. #ifdef _MSC_VER
  67. #define DISP_CLEAR system("cls")
  68. #else
  69. #define DISP_CLEAR system("clear")
  70. #endif
  71.  
  72. using namespace std;

Split

  1. //標準入力から読み込んだ文字を任意の文字で分割する
  2. vector<string> split(char split_char){
  3. string str;
  4. vector<string> res;
  5. ifstream ifs(stdin);
  6. size_t current = 0, found;
  7.  
  8. getline(ifs, str);
  9.  
  10. while((found = str.find_first_of(split_char, current)) != string::npos)
  11. {
  12.  
  13. res.push_back(string(str, current, found - current));
  14. current = found + 1;
  15.  
  16. }
  17.  
  18. res.push_back(string(str, current, str.size() - current));
  19. return res;
  20. }
  21.  
  22.  
  23. int main(void){
  24. ios::sync_with_stdio(false);
  25.  
  26. /* start */
  27.  
  28. vector<string> arr;
  29.  
  30. cout << "空白区切りで入力:";
  31. arr = split(' ');
  32. for(int i=0;i<arr.size();i++)cout << arr[i] << endl;
  33.  
  34. cout << "カンマ区切りで入力:";
  35. arr = split(',');
  36. for(int i=0;i<arr.size();i++)cout << arr[i] << endl;
  37.  
  38. /* end */
  39.  
  40. return 0;
  41. }
  42.  

2線分の交点

  1. //p1(a,b) p2(c,d)
  2. //p3(e,f) p4(g,h)
  3. bool _inline crossSegment(double a, double b, double c, double d, double e, double f, double g, double h){
  4. bool foo=false;
  5. double A,B,C;
  6. double x,y;
  7.  
  8. fprintf(stderr, "( %.2f , %.2f ) ", a, b);
  9. fprintf(stderr, "( %.2f , %.2f ) ", c, d);
  10. fprintf(stderr, "( %.2f , %.2f ) ", e, f);
  11. fprintf(stderr, "( %.2f , %.2f ) => ", g, h);
  12.  
  13. A = f*g-e*h;
  14. B = b*c-a*d;
  15. C = (d-b)*(g-e)-(c-a)*(h-f);
  16.  
  17. if(C == 0){
  18. fprintf(stderr, "N/A \n");
  19. return false;
  20. }
  21.  
  22. x = ( A*(c-a) - B*(g-e) ) / C;//交点のx座標
  23. y = ( A*(d-b) - B*(h-f) ) / C;//交点のy座標
  24.  
  25. fprintf(stderr, "( %.2f , %.2f )", x, y);
  26.  
  27. /* ((a<x<c)||(c<x<a)) && ((e<x<g)||(g<x<e)) */
  28. if( ((a <= x && x <= c) || (c <= x && x <= a)) && ((e <= x && x <= g) || (g <= x && x <= e)) ){
  29. foo = true;
  30. }else{
  31. foo = false;
  32. }
  33.  
  34. foo ? cerr << "cross" << endl : cerr << "not cross" << endl;
  35. cerr << endl;
  36.  
  37. return foo;
  38. }
  39.  


実行時間の計測(秒単位)

  1. class MyTime{
  2. struct tm *t;
  3. time_t start, end, tmp;
  4. public:
  5. MyTime();
  6. void MeasurementStart();//計測の開始
  7. void MeasurementEnd();//計測の終了
  8. void PrintRuntime();//標準エラー出力で時間を表示
  9. int getDifftime();//経過秒数をint型で返す
  10. void PrintLocalTime();//現在時刻を表示する
  11. void PrintStartTime();//計測の開始時刻を表示する
  12. void SleepSec(int sec);//sec秒だけ処理を停止
  13. };
  14.  
  15. MyTime::MyTime(){
  16. start = time(NULL);
  17. end = time(NULL);
  18. tmp = time(NULL);
  19. t = NULL;
  20. };
  21.  
  22. void MyTime::MeasurementStart(){
  23. time( &start );
  24. };
  25.  
  26. void MyTime::MeasurementEnd(){
  27. time( &end );
  28. };
  29.  
  30. void MyTime::PrintRuntime(){
  31. int tmp = (int)difftime(end, start);
  32. int hour, min, sec;
  33. hour = tmp / 3600;
  34. tmp -= hour * 3600;
  35. min = tmp / 60;
  36. sec = tmp % 60;
  37. fprintf(stderr, "%5dH %2dM %2dS", hour, min, sec );
  38. };
  39.  
  40. int MyTime::getDifftime(){
  41. return (int)difftime(end, start);
  42. };
  43.  
  44. void MyTime::PrintLocalTime(){
  45. time( &tmp );
  46. t = localtime( &tmp );
  47. fprintf(stderr, "%s", asctime(t) );
  48. }
  49.  
  50. void MyTime::PrintStartTime(){
  51. t = localtime( &start );
  52. fprintf(stderr, "%s", asctime(t) );
  53. }
  54.  
  55. void MyTime::SleepSec(int sec){
  56.  
  57. #ifdef _MSC_VER
  58. Sleep((int)sec * 1000);
  59. #else
  60. sleep((int)sec);
  61. #endif
  62. }
  63.  
  64.  

実行時間の計測

  1. #include <cstdio>
  2. #include <ctime>
  3. #include <iostream>
  4. #include <iomanip>
  5. #include <windows.h>
  6.  
  7. using namespace std;
  8.  
  9. void print_run_time(clock_t start, clock_t end){
  10. cout << "[";
  11. cout << (end - start)/1000/60/60 << "h ";
  12. cout << setw(2) << ((end - start)/1000/60)%60 << "m ";
  13. cout << setw(2) << ((end - start)/1000)%60 << "s] ";
  14.  
  15. cout << "[" << (double)(end - start)/1000. << "s]" << endl;
  16. }
  17.  
  18.  
  19. int main(){
  20. srand((unsigned int)time(NULL));
  21. clock_t c_start,c_end;
  22. c_start = clock();
  23. /* 計測したい処理 */
  24. c_end = clock();
  25.  
  26.  
  27. print_run_time(c_start, c_end);
  28. return 0;
  29. }
  30.  

コンソール表示色の変更

サンプル1

  1. template <class X> void printColor(X out, int flag) {
  2. HANDLE hStdout;
  3. WORD white, red, blue, green, yellow, pink, aqua, tmp;
  4. CONSOLE_SCREEN_BUFFER_INFO csbi;
  5. hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  6. GetConsoleScreenBufferInfo(hStdout, &csbi);
  7.  
  8. white = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
  9. red = FOREGROUND_INTENSITY | FOREGROUND_RED;
  10. green = FOREGROUND_INTENSITY | FOREGROUND_GREEN;
  11. blue = FOREGROUND_INTENSITY | FOREGROUND_BLUE;
  12. yellow = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN;
  13. pink = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE;
  14. aqua = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE;
  15.  
  16. switch(flag){
  17. case 1:
  18. tmp = white;
  19. break;
  20. case 2:
  21. tmp = red;
  22. break;
  23. case 3:
  24. tmp = blue;
  25. break;
  26. case 4:
  27. tmp = green;
  28. break;
  29. case 5:
  30. tmp = yellow;
  31. break;
  32. default:
  33. tmp = csbi.wAttributes;
  34. }
  35.  
  36.  
  37. SetConsoleTextAttribute(hStdout, tmp);
  38. cout << out << '\n';
  39. SetConsoleTextAttribute(hStdout, csbi.wAttributes);
  40. }
  41.  



サンプル関数(100までの整数をゲージで表示)

  1. #include <windows.h>
  2. #include <stdio.h>
  3. #include <conio.h>
  4.  
  5. void gauge(int x){
  6. HANDLE hStdout;
  7. WORD white, red, blue, green, yellow, pink, aqua;
  8. CONSOLE_SCREEN_BUFFER_INFO csbi;
  9. hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  10. GetConsoleScreenBufferInfo(hStdout, &csbi);
  11.  
  12. //各色の定義
  13. white = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
  14. red = FOREGROUND_INTENSITY | FOREGROUND_RED;
  15. green = FOREGROUND_INTENSITY | FOREGROUND_GREEN;
  16. blue = FOREGROUND_INTENSITY | FOREGROUND_BLUE;
  17. yellow = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN;
  18. pink = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE;
  19. aqua = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE;
  20.  
  21. if(x < 0 || 100 < x){
  22. return;
  23. }else{
  24. SetConsoleTextAttribute(hStdout, white);
  25. cout << "|";
  26. SetConsoleTextAttribute(hStdout, blue);
  27. for(int i=0;i<100;i+=2){
  28. if(i > 20)SetConsoleTextAttribute(hStdout, aqua);
  29. if(i > 40)SetConsoleTextAttribute(hStdout, green);
  30. if(i > 60)SetConsoleTextAttribute(hStdout, yellow);
  31. if(i > 80)SetConsoleTextAttribute(hStdout, red);
  32.  
  33. if(i <= x)cout << ">";
  34. else cout << " ";
  35. }
  36. SetConsoleTextAttribute(hStdout, white);
  37. cout << "|" << endl;
  38. }
  39.  
  40. //元のテキスト状態に戻す
  41. SetConsoleTextAttribute(hStdout, csbi.wAttributes);
  42. }
  43.  

cin/coutの高速化

c++で標準入力・出力にはcin/coutを使用することが多いが,この関数は実行速度が速くない.
そのため,main関数の初めにあるフレーズを挿入することで高速化が可能である.
  1. int main(){
  2. ios::sync_with_stdio(false);//main関数の最初に記述
  3.  
  4. //処理
  5.  
  6. return 0;
  7. }
  8.  

最大公約数(GCD)

  1. int gcd(int x, int y)
  2. {
  3. int tmp;
  4. // ユーグリッド互除法
  5. while((tmp = x % y) != 0){
  6. x = y;
  7. y = tmp;
  8. }
  9. return y;
  10. }
  11.  
  12. int main()
  13. {
  14. int x, y;
  15. int num=0;
  16. while(!num){
  17. cin >> x >> y;
  18. num = gcd(x, y);
  19. }
  20. cout << num << endl;
  21. return 0;
  22. }
  23.  

素数

MAXまでの素数をあらかじめ,計算しておく関数.(改善の余地あり)
  1. #define MAX 1000000
  2. int main(void){
  3. /* start */
  4. int num=2;
  5. bool check[MAX+2];
  6. vector<int> arr;
  7. while(num < MAX){
  8. if(!check[num]){
  9. int tmp=num;
  10. arr.push_back(num);
  11. while(tmp<MAX){
  12. check[tmp]=true;
  13. tmp+=num;
  14. }
  15. }
  16. num++;
  17. }
  18. //for(i=0;i<arr.size();i++)cout << arr[i] << endl;//素数の表示
  19. cout << arr.size() << endl;//素数の数の表示
  20. /* end */
  21. return 0;
  22. }
  23.  

階乗・コンビネーション

  1. int kaijou(int n){
  2. if(n == 1)return 1;
  3. else return n*kaijou(n-1);
  4. }
  5.  
  6. int combination(int n, int m){//nCm
  7. int tmp1,tmp2,tmp3;
  8. tmp1 = kaijou(n);
  9. tmp2 = kaijou(n-m);
  10. tmp3 = kaijou(m);
  11. return tmp1 / tmp2 / tmp3;
  12. }
  13.  

2次元配列のnewによる動的生成の例


多次元配列をnewによって動的に生成する為に思いつくのは(例1)のような記述の仕方であるが,
そのように記述してもエラーが出てしまうため(例2)のように記述する必要がある.

例1
  1. double **arr;
  2. arr = new double[size_x][size_y];

例2
  1. double **arr = new double*[size_x];
  2. for (int i = 0; i < size_x; i++) {
  3. arr[i] = new double[size_y];
  4. }
  5. //配列の使用
  6. for (int i = 0; i < size_x; i++) {
  7. delete[] arr[i];
  8. }
  9. delete[] arr;

ファイルの検索および検索結果のstringへの格納

  1. #include <vector>
  2. #include <string>
  3. #include <io.h>
  4. #include <iostream>
  5. using namespace std;
  6.  
  7. void find_file();
  8.  
  9. vector<string> arr;
  10.  
  11. int main(){
  12. find_file();
  13.  
  14. for(int i=0;i<arr.size();i++){
  15. cout << arr[i] << endl;
  16. }
  17.  
  18. return 0;
  19. }
  20.  
  21. void find_file()
  22. {
  23. long handle;
  24. struct _finddata_t finddata;
  25.  
  26. handle = _findfirst("*.txt", &finddata);
  27. if(handle != -1){
  28. arr.push_back(finddata.name);
  29. while(_findnext(handle, &finddata) != -1){
  30. arr.push_back(finddata.name);
  31. }
  32. _findclose(handle);
  33. }
  34. }
  35.  


日付の取得・表示


  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <iostream>
  5. #include <sstream>
  6. #include <string>
  7. #include <windows.h>
  8.  
  9. using namespace std;
  10.  
  11. //int型をstring型に変換
  12. string IntToString(int number)
  13. {
  14. stringstream ss;
  15. ss << number;
  16. return ss.str();
  17. }
  18.  
  19. //日付をstring型で返す
  20. string DateTimeString(void)
  21. {
  22. string strtmp = "";
  23. time_t timer;
  24. struct tm *date;
  25. char ch[256];
  26.  
  27. /* 時間を取得 */
  28. timer = time(NULL);
  29.  
  30. /* 構造体 date に変換 */
  31. date = localtime(&timer);
  32.  
  33.  
  34. strtmp += IntToString(date->tm_year + 1900) + "_";
  35.  
  36. if(date->tm_mon + 1 < 10)strtmp += "0" + IntToString(date->tm_mon + 1);
  37. else strtmp += IntToString(date->tm_mon + 1);
  38.  
  39. if(date->tm_mday < 10)strtmp += "0" + IntToString(date->tm_mday) + "_";
  40. else strtmp += IntToString(date->tm_mday) + "_";
  41.  
  42. if(date->tm_hour < 10)strtmp += "0" + IntToString(date->tm_hour);
  43. else strtmp += IntToString(date->tm_hour);
  44.  
  45.  
  46. if(date->tm_min < 10)strtmp += "0" + IntToString(date->tm_min) + "_";
  47. else strtmp += IntToString(date->tm_min) + "_";
  48.  
  49. if(date->tm_sec < 10)strtmp += "0" + IntToString(date->tm_sec);
  50. else strtmp += IntToString(date->tm_sec);
  51.  
  52. return strtmp;
  53. }
  54.  
  55. int main(){
  56.  
  57. while(1){
  58. system("cls");
  59. cout << DateTimeString() << endl;
  60. Sleep(1000);
  61. }
  62.  
  63. return 0;
  64. }
  65.  
  66.  
  67.  
最終更新:2012年12月27日 11:49
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。