C++ part B 第一周(下)

本文深入探讨了STL中reverse()和sort()算法的工作原理,通过实例展示了如何使用这些算法来反转元素顺序和检查回文序列,同时讲解了双向迭代器和随机访问迭代器的区别及其在算法中的应用。

reverse()

A canonical algorithm using this iterator is the STL reverse() algorithm:

template<typename T>
void reverse(BidirectionalIterator first, BidirectionalIterator last); 

This algorithm reverses the elements in the specified iterator range.

 

Front++

Back--

So swap and move would lead to reverse

#include<iostream>
#include<vector>

using namespace std;

template<typename Bidirectional>
bool isPalindrome(Bidirectional first, Bidirectional last){
    while(true){
        last--;
        if(first==last) //assume >= undefined
        break;
        if(*first!=*last)
        return false;
        first++;
        if(first==last)
        break;
    }
    return true;
}

int main(){
    vector<int> s = {1, 2, 2, 1};
    cout << isPalindrome(s.begin(), s.end());
}

The algorithm moves forward and backward testing each position for equality

it checks if a value is not equal and returns false

if all values test as equal then the iterators "meet in the middle"(or pass each other) and it returns true

Compare to how you would do this with a forward only iterator - becomes n*n

 

The random access iterator must allow the elements to be randomly searched in fixed time. Think indexed array.

This requires effectively bing able to add or subtract to an iterator value and retrieve a value from the computed position.

It also means that iterator values can be compared for less and greater than as well as queality operators

 

A canonical algorithm using this iterator is the STL sort() algorithm:

template<class RandomAccessIterator>
void sort(RandomAccessIterator first, RandomAccessIterator last);
#include<iostream>
#include<vector>
#include<random>
#include<ctime>

using namespace std;

template<typename RandomAccess>
RandomAccess pickRandEI(RandomAccess first, RandomAccess last){
    ptrdiff_t temp = last-first;
    return first + rand()%temp;
}

int main(){
    srand(time(0));
    vector<int> myvector = {1, 2, 3, 4, 5, 6};
    auto it = pickRandEI(myvector.begin(), myvector.end());
    cout << *it << endl;
}

#include<cstddef> //ptrdiff_t

ptrdiff_t.type.<cstddef>.Result of pointer subtraction. This is the type returned by the subtraction operation between two pointers.This is a signed integral type.

转载于:https://www.cnblogs.com/freeblacktea/p/10308131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值