求vector的最大值
调用algorithm
中的max_elment
1 2
| vector<int> num = {......}; int max = *max_element(num.begin(),num.end());
|
使用getline
调用sstream
包的字符串流和fstream
的文件输出流
1 2 3 4 5 6
| std::ifstream file(file_name); std::stringstream ss; type x,y; while(getline(file,ss)){ ss>>x>>y; }
|
使用sort进行排序
下面是一个使用sort
对一个vector<pair<int,int>>
的vector
按照第一个元素的大小进行排序的例子
1 2 3 4
| vector<pair<int, int>> vec = {{3, 10}, {1, 20}, {4, 15}, {2, 30}}; sort(vec.begin(),vec.end(),[](const pair<int,int> &a ,const pair<int,int> &b){ return a.first > b.first })
|
vector的初始化
std::vector提供了一个可以指定元素个数和初始值的构造函数,函数签名如下,第一个是元素个数,第二个是元素的初始值
1
| std::vector<Type> vec(size_t count,const Type& value);
|
计时
1 2 3 4 5 6 7 8 9 10
| #include <chrono> #include <thread> int main(){ using namespace std::literals::chrono_literals; auto start = std::chrono::high_resolution_clock::now(); std::this_thread::sleep_for(1s); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<float> duration = end - start; std::cout<<duration.count()<<"s"<<std::endl; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #include <iostream> #include <chrono> using namespace std;
void some_function() { for (int i = 0; i < 1000000; ++i) {} }
int main() { auto start = chrono::high_resolution_clock::now();
some_function();
auto end = chrono::high_resolution_clock::now();
auto duration_micro = chrono::duration_cast<chrono::microseconds>(end - start); cout << "Time taken: " << duration_micro.count() << " microseconds" << endl;
auto duration_milli = chrono::duration_cast<chrono::milliseconds>(end - start); cout << "Time taken: " << duration_milli.count() << " milliseconds" << endl;
auto duration_sec = chrono::duration_cast<chrono::seconds>(end - start); cout << "Time taken: " << duration_sec.count() << " seconds" << endl;
return 0; }
|