直接用法
- lower_bound :
返回大于或等于val的第一个元素位置
如[2, 2, 5, 5, 5, 8, 8]中找5返回2, 找4返回2 - upper_bound:
返回大于val的第一个元素位置
如[2, 2, 5, 5, 5, 8, 8]中找5返回5, 找4返回2 stringstream:
把东西放进缓存区, 方便再读出来
如#include <cstdio> #include <iostream> #include <sstream> using namespace std; int main() { stringstream buf; string in; while(getline(cin, in)) { buf << in; string tmp; while(buf >> tmp) cout << tmp << endl; } }
删除文件 删除所有除了.cpp以外的文件 慎用 可能把系统文件之类的东西也删除了!!!!
#include <bits/stdc++.h> #include <windows.h> int find_all_files(const char * lpPath) { char szFind[MAX_PATH]; WIN32_FIND_DATA FindFileData; strcpy(szFind,lpPath); strcat(szFind,"\\*.*"); HANDLE hFind=::FindFirstFile(szFind,&FindFileData); if(INVALID_HANDLE_VALUE == hFind) return -1; do { if(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if(strcmp(FindFileData.cFileName,".")!=0 && strcmp(FindFileData.cFileName, "..")!=0) { //发现子目录,递归之 char szFile[MAX_PATH] = {0}; strcpy(szFile,lpPath); strcat(szFile,"\\"); strcat(szFile,FindFileData.cFileName); find_all_files(szFile); } } else { //找到文件,处理之 int ok = 1; char tmp[MAX_PATH] = {0}; strcpy(tmp, lpPath); strcat(tmp, "\\"); strcat(tmp, FindFileData.cFileName); int len = strlen(tmp); if((len >= 4) && tmp[len-1] == 'p' && tmp[len-2] == 'p' && tmp[len-3] == 'c' && tmp[len-4] == '.') ok = 0; if(ok) { if(remove(tmp)) std::cout << "failed remove " << tmp << std::endl; else std::cout << "succeed remove " << tmp << std::endl; } // std::cout << lpPath << "\\" << FindFileData.cFileName << std::endl; } }while(::FindNextFile(hFind,&FindFileData)); ::FindClose(hFind); return 0; } int main() { char s[MAX_PATH]; gets(s); for(int i = 0; s[i]; ++i) { if(s[i] == '\\') { int len = strlen(s); for(int j = len; j - i; --j) s[j] = s[j-1]; s[len+1] = '\0'; ++i; } } find_all_files(s); }
计算程序的运行时间(精确到毫秒)
#include <time.h> #include <cstdio> int main() { double s, t; s = clock();//得到开始时间 int times = 1e9; printf("run %d times = ", times); for(int i = 0; i < times; ++i) ; t = clock();//得到结束时间 printf("%f seconds\n", (t - s) * 1000 / CLOCKS_PER_SEC); }
lower_bound
- 先给图
lower_bound(有这元素)
lower_bound(没这个元素)
函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置(返回查找元素的第一个可安插位置);
upper_bound(有这个元素)
upper_bound(没这个元素)
upper_bound(返回刚好大于这个元素的位置) 实现
假设a是一个数组
格式: iterator res = lower_bound(a_first, a_last, val) a_first和a_last都是迭代器(当然也可以是指针) val是要找的值 那么就会得到a[res] == val并且res取最小值- 标准库的实现:
- 标准库的实现:
- 下面是手写的实现:
upper_bound
手写的upper_bound小于改等于就可以了
标准库的不是改成等于, 不过相差不多
- PS
元素个数等于upper_bound - lower_boudn
(数组中有3个2)
stringstream
别人介绍得很好 : http://www.cppblog.com/Sandywin/archive/2007/07/13/27984.html