《quantitative finance with cpp》阅读笔记19---反转列表元素的顺序
作者:yunjinqi   类别:    日期:2024-01-01 10:17:22    阅读:469 次   消耗积分:0 分    

Write a function reverseDoubles which takes a pointer to a list of doubles and the length of the list and reverses it. So (1, 2, 3, 4) should be changed to (4, 3, 2, 1), for example. Write a test for this function。


这个是要求反转链表中的double类型的元素,实际上采用reverse更方便,也存在其他更高级的一些写法。下面代码仅供参考:


list<double> reverseDoubles(list<double>& l, int length) {
    /* Write a function reverseDoubles which takes a pointer to a list of
    doubles and the length of the list and reverses it. So (1, 2, 3, 4) should be
    changed to (4, 3, 2, 1), for example. Write a test for this function.
    其实list存在函数reverse可以直接实现这个需求,不需要重复写函数
    */
    list<double> l2;
    for (auto v : l) {
        l2.push_front(v);
    }
    return l2;
}

void testReverseDoubles() {
    list<double> l = { 1.0,2.0,3.0,4.0 };
    list<double> l2 = reverseDoubles(l, 4);
    list<double> l3 = { 4.0,3.0,2.0,1.0 };
    ASSERT(l2 == l3);
}


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/384
上一篇:《quantitative finance with cpp》阅读笔记18---使用指针作为参数进行求和
下一篇:《quantitative finance with cpp》阅读笔记20---计算一系列点离原点的平均距离