码迷,mamicode.com
首页 > 编程语言 > 详细

C++ part B 第一周(下)

时间:2019-01-23 12:31:46      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:this   direction   main   fir   undefined   think   rand   names   site   

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.

C++ part B 第一周(下)

标签:this   direction   main   fir   undefined   think   rand   names   site   

原文地址:https://www.cnblogs.com/freeblacktea/p/10308131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!