练习 3.1 给定一个表L和另一个表P,他们包含以升序排列的整数。
操作printLots(L,p)将打印L中那些由P所指定的位置上的元素。例如,如果P=1,3,4,6,那么L中位于第1个,第3个,第4个和第6个位置上的元素就被打印出来。
写出过程printLots(L,P).只可使用共有型STL 容器操作。该过程的运行时间是多少?
#include <list>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <chrono>
using namespace std;
using namespace chrono;
void printLists(const list<int>&l1, const list<int> &l2)
{
cout << "list1: ";
copy(l1.cbegin(), l1.cend(), ostream_iterator<int>(cout, " "));
cout << endl << "list2: ";
copy(l2.cbegin(), l2.cend(), ostream_iterator<int>(cout, " "));
cout << endl << endl;
}
void printLots(const list<int> & lhs, const list<int> &phl)
{
for (auto rgt = phl.begin(); rgt != phl.end(); rgt++)
{
auto lft = lhs.begin();
size_t count = 0;
while (count < *rgt)
{
lft++;
count++;
}
cout << *(--lft) << endl;
}
}
int main()
{
list<int> list1 = { 11,12,13,14,15,16,17,18,19,20 }, plst2 = {1,3,4,6};
printLists(list1, plst2);
auto start = system_clock::now();
for(size_t i=0;i<1000;i++)
printLots(list1, plst2);
auto end = system_clock::now();
auto duration = duration_cast<microseconds>(end - start);
cout << " Consume: " << double(duration.count())*microseconds::period::num / microseconds::period::den << " s(秒)";
cout << endl;
return 0;
}
学校的这台i5 老机器 Consume: 0.312s .