algorithm之改变序列算法--待解决

简述:改变序列算法,参见http://www.cplusplus.com/reference/algorithm/?kw=algorithm

待解决问题:iterator_traits、std::move

/*
template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator partition (BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred);

Partition range in two
[将一个区间一分为二]
Rearranges the elements from the range [first,last), in such a way that all the elements for which pred returns true precede all those for which it returns false. The iterator returned points to the first element of the second group.
该算法用来将一个序列分成两个部分,其中第1个部分为使得pred()返回true的元素,第2个部分为使得pred()返回false的元素,该算法返回指向第一个使得pred()返回false的元素的迭代器]
The relative ordering within each group is not necessarily the same as before the call. See stable_partition for a function with a similar behavior but with stable ordering within each group.
[该算法作用后,每一部分元素的相对排序与调用算法之前元素的相对排序不一定是一样的。如果想要保持元素的相对排序,请参看stable_partition]
The behavior of this function template (C++98) is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator partition (BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred)
{
    while(first != last){
        while(pred(*first)){
            ++first;
            if(first == last)    return first;
        }
        do{
            --last;
            if(first == last)    return first;
        }while(!pred(*last));
        swap(*first, *last);
        ++first;
    }
    return first;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

bool isOdd(int i){
    return (i%2 == 1);
}

int main()
{
    std::vector<int> myvector;
    std::vector<int>::iterator it, bound;

    for(int i=1; i<10; i++)    myvector.push_back(i);

    bound = std::partition(myvector.begin(), myvector.end(), isOdd);

    std::cout<<"odd elements:";
    for(it = myvector.begin(); it != bound; ++it)
        std::cout<<*it<<' ';
    std::cout<<'\n';

    std::cout<<"even elements:";
    for(it = bound; it != myvector.end(); ++it)
        std::cout<<*it<<' ';
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class BidirectionalIterator, class UnaryPredicate>
BidirectionalIterator stable_partition (BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred);

Partition range in two - stable ordering
Rearranges the elements in the range [first,last), in such a way that all the elements for which pred returns true precede all those for which it returns false, and, unlike function partition, the relative order of elements within each group is preserved.
[该算法用来将一个序列分成两个部分,其中第1个部分为使得pred()返回true的元素,第2个部分为使得pred()返回false的元素,不同于partition(),该函数会保留元素的相对排序]
This is generally implemented using an internal temporary buffer.
[该函数通常是使用一个内部的临时缓冲实现的]
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::stable_partition
#include <vector>       // std::vector

bool IsOdd (int i) { return (i%2)==1; }

int main () 
{
    std::vector<int> myvector;

    // set some values:
    for (int i=1; i<10; ++i) myvector.push_back(i); // 1 2 3 4 5 6 7 8 9

    std::vector<int>::iterator bound;
    bound = std::stable_partition (myvector.begin(), myvector.end(), IsOdd);

    std::cout << "odd elements:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=bound; ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    std::cout << "even elements:";
    for (std::vector<int>::iterator it=bound; it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result);

Copy range of elements
[copy区间中的元素]
Copies the elements in the range [first,last) into the range beginning at result.
[将区间[first, last)中的元素复制到result所指向的起始位置]
The function returns an iterator to the end of the destination range (which points to the element following the last element copied).
[该函数的返回一个指向目标区间的尾部的迭代器(即指向目标区间中最后一个元素的下一位)]
The ranges shall not overlap in such a way that result points to an element in the range [first,last). For such cases, see copy_backward.
[result不应该指向区间[first, last)中的元素,即拷贝区间不允许这种形式的重叠。对于这种重叠情况,请看copy_backward]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class InputIterator, class OutputIterator>
OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result)
{
    while(first != last){
        *first = *result;
        ++first;    ++result;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main () 
{
    int myints[]={10,20,30,40,50,60,70};
    std::vector<int> myvector (7);

    std::copy ( myints, myints+7, myvector.begin() );

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it = myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward (BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result);

Copy range of elements backward
[反向拷贝区间中的元素]
Copies the elements in the range [first,last) starting from the end into the range terminating at result.
[从后向前将区间[first, last)中的元素拷贝到以result为结尾的另一区间中]
The function returns an iterator to the first element in the destination range.
[该函数返回一个指向目标区间的第一个元素的迭代器]
The resulting range has the elements in the exact same order as [first,last). To reverse their order, see reverse_copy.
[目标区间中的元素排序与[first, last)中的完全一样,如果需要反转拷贝,请参看reverse_copy]
The function begins by copying *(last-1) into *(result-1), and then follows backward by the elements preceding these, until first is reached (and including it).
[该函数从(last-1)处开始拷贝元素到(result-1)处,然后前向拷贝,直到到达first]
The ranges shall not overlap in such a way that result (which is the past-the-end element in the destination range) points to an element in the range (first,last]. For such cases, see copy.
[result(目标区间的最后一个元素的下一位)不应该指向[first, last)中的元素,即不允许这种情况的重叠;对于这种重叠情况,请看copy]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward (BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result)
{
    while(last != first){
        *(--result) = *(--last);
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> myvector;
    std::vector<int>::iterator it;

    for (int i=1; i<=5; i++)    
        myvector.push_back(i*10);          // myvector: 10 20 30 40 50

    myvector.resize(myvector.size()+3);

    std::copy_backward(myvector.begin(), myvector.begin()+5, myvector.end());

    std::cout << "myvector contains:";
    for (it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class T>
void swap (T& a, T& b);

Exchange values of two objects
[交换两个对象的值]
Exchanges the values of a and b.
[交换a和b的值]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class T>
void swap (T& a, T& b)
{
    T c(a);    a = b;    b = c;
}
Notice how this function involves a copy construction and two assignment operations, which may not be the most efficient way of swapping the contents of classes that store large quantities of data, since each of these operations generally operate in linear time on their size.
[该函数包含一个复制构造和两个赋值操作,如果要交换的类包含大量数据,这就不是最有效的方式,因为这些操作的时间复杂度一般是线性的]
Large data types can provide an overloaded version of this function optimizing its performance. Notably, all standard containers specialize it in such a way that only a few internal pointers are swapped instead of their entire contents, making them operate in constant time.
[大数据类型可以提供一个该函数的重载形式来优化其表现。尤其是标准容器都会特化这个模板函数,在内部实现中通过交换一些内部指针来代替交换整个内容,使得该操作的时间复杂度为一个常数]
Many components of the standard library (within std) call swap in an unqualified manner to allow custom overloads for non-fundamental types to be called instead of this generic version: Custom overloads of swap declared in the same namespace as the type for which they are provided get selected through argument-dependent lookup over this generic version.
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int x=10, y=20;                              // x:10 y:20
    std::swap(x,y);                              // x:20 y:10

    std::vector<int> foo (4,x), bar (6,y);       // foo:4x20 bar:6x10
    std::swap(foo,bar);                          // foo:6x10 bar:4x20

    std::cout << "foo contains:";
    for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2);

Exchange values of two ranges
[交换两个区间中的值]
Exchanges the values of each of the elements in the range [first1,last1) with those of their respective elements in the range beginning at first2.
[将区间[first, lasL)中的元素与以first2开始的等长范围内的元素进行交换]]
The function calls swap (unqualified) to exchange the elements.
[该函数调用swap()来进行元素的交换]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator2 swap_ranges (ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2)
{
    while(first1 != last1){
        swap(*first1, *first2);
        ++first1;    ++first2;
    }
    return first2;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> foo(5, 10);
    std::vector<int> bar(5, 30);
    std::vector<int>::iterator it;

    std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin());

    std::cout<<"foo contains:";
    for(it = foo.begin(); it != foo.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    std::cout<<"bar contains:";
    for(it = bar.begin(); it != bar.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator1, class ForwardIterator2>
void iter_swap (ForwardIterator1 a, ForwardIterator1 b);

Exchange values of objects pointed to by two iterators
[交换两个迭代器所指向的对象的值]
Swaps the elements pointed to by a and b.
[交换迭代器a和b所指向的元素]
The function calls swap (unqualified) to exchange the elements.
[该函数调用swap()来实现元素的交换]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator1, class ForwardIterator1>
void iter_swap (ForwardIterator1 a, ForwardIterator1 b)
{
    swap(*a, *b);
}
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::iter_swap
#include <vector>       // std::vector

int main () {

    int myints[]={10,20,30,40,50 };               //   myints:  10  20  30  40  50
    std::vector<int> myvector (4,99);            // myvector:  99  99  99  99

    std::iter_swap(myints,myvector.begin());     //   myints: [99] 20  30  40  50
                                                                     // myvector: [10] 99  99  99

    std::iter_swap(myints+3,myvector.begin()+2); //   myints:  99  20  30 [99] 50
                                                                         // myvector:  10  99 [40] 99

    ostream_iterator

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator, class UnaryOperation >
OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op);

template <class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation>
OutputIterator transform (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, OutputIterator result, BinaryOperation binary_op);

Transform range
[转换区间]
Applies an operation sequentially to the elements of one (1) or two (2) ranges and stores the result in the range that begins at result.
[将一个操作一次应用于区间中的每个元素,并将结果保存在以result开始的区间中]
(1) unary operation
[形式一:一元操作]
Applies op to each of the elements in the range [first1,last1) and stores the value returned by each operation in the range that begins at result.
[将一元操作应用与[first1, last1)中的每个元素,并将结果保存在以result开始的区间中]
(2) binary operation
[形式二:二元操作]
Calls binary_op using each of the elements in the range [first1,last1) as first argument, and the respective argument in the range that begins at first2 as second argument. The value returned by each call is stored in the range that begins at result.
[将[ffirst, last1)中的每个元素作为二元操作的第一个参数,并将以first2开始的相应区间中的每个元素作为二元操作的第二个参数,运算结果保存在以result开始的区间中]
The behavior of this function template is equivalent to:
[该模板函数的行为等价于以下操作:]
template <class InputIterator, class OutputIterator, class UnaryOperation >
OutputIterator transform (InputIterator first1, InputIterator last1, OutputIterator result, UnaryOperation op)
{
    while(first1 != last1){
        *result = op(*first1);
        ++first1;    ++result;
    }
    return result;
}
The function allows for the destination range to be the same as one of the input ranges to make transformations in place.
[该函数允许目标区间与输入区间相同来进行转换]
*/

#include <iostream>
#include <algorithm>
#include <vector>

int op_increase(int i){
    return ++i;
}

int binaryop_add(int i, int j){
    return (i+j);
}

int main()
{
    std::vector<int> foo;
    std::vector<int> bar;

    for(int i=1; i<6; i++)    foo.push_back(i*10);     // foo: 10 20 30 40 50

    bar.resize(foo.size());

    std::transform(foo.begin(), foo.end(), bar.begin(), op_increase);    // bar: 11 21 31 41 51

    std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(), binaryop_add);     // foo: 21 41 61 81 101

    std::cout << "foo contains:";
    for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T & new_value)

Replace value in range
Assigns new_value to all the elements in the range [first,last) that compare equal to old_value.
[将区间[first, last)中值为old_value的元素替换为值为new_value的元素]
The function uses operator== to compare the individual elements to old_value.
[该函数使用operator==来比较每个元素是否相等]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class T>
void replace (ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value)
{
    while(first != last){
        if(*first == old_value)    *first = new_value;
        ++first;
    }
}
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::replace
#include <vector>       // std::vector

int main () {
    int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
    std::vector<int> myvector (myints, myints+8);            // 10 20 30 30 20 10 10 20

    std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value );

Replace values in range
Assigns new_value to all the elements in the range [first,last) for which pred returns true.
[将[first, last)中使得pred()返回真的元素替换为new_value]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class UnaryPredicate, class T>
void replace_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value )
{
    while(first != last){
        if(pred(*first))    *first = new_value;
        ++first;
    }
}
*/

#include <iostream>
#include <vector>
#include <algorithm>

bool IsOdd (int i){
    return (i%2 == 1);
}

int main()
{
    std::vector<int> myvector;

    for(int i=1; i<10; i++)    myvector.push_back(i);

    std::replace_if(myvector.begin(), myvector.end(), IsOdd, 0);

    std::cout<<"myvector contains:";
    for(std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value);

Copy range replacing value
Copies the elements in the range [first,last) to the range beginning at result, replacing the appearances of old_value by new_value.
[将[first, last)中的元素拷贝到以result开始的区间中,并替换old_value为new_value]
The function uses operator== to compare the individual elements to old_value.
[该函数使用operator==来判断元素是否为old_value]
The behavior of this function template is equivalent to:
[该函数模板的行为等价与以下操作:]
template <class InputIterator, class OutputIterator, class T>
OutputIterator replace_copy (InputIterator first, InputIterator last, OutputIterator result, const T& old_value, const T& new_value)
{
    while(first != last){
        *result = (*first  == old_value)?new_value:*first;
        ++first;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 };
    std::vector<int> myvector(8);

    std::replace_copy(myints, myints+8, myvector.begin(), 20, 99);

    std::cout<<"myvector contains:";
    for(std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
OutputIterator replace_copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred, const T& new_value);

Copy range replacing value
Copies the elements in the range [first,last) to the range beginning at result, replacing those for which pred returns true by new_value.
[将[first, last)中的元素拷贝到以result起始的区间中,并替换其中使得pred()返回真的元素为new_value]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class InputIterator, class OutputIterator, class UnaryPredicate, class T>
OutputIterator replace_copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred, const T& new_value)
{
    while(first != last){
        *result = (pred(*first))?new_value:*first;
        ++first;    ++result;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
    std::vector<int> foo,bar;

    // set some values:
    for (int i=1; i<10; i++) foo.push_back(i);          // 1 2 3 4 5 6 7 8 9

    bar.resize(foo.size());   // allocate space
    std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0);    // 0 2 0 4 0 6 0 8 0

    std::cout << "bar contains:";
    for (std::vector<int>::iterator it=bar.begin(); it!=bar.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
std::fill
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val);

Fill range with value
Assigns val to all the elements in the range [first,last).
[将val赋值给[first, last)之间的所有元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class T>
void fill (ForwardIterator first, ForwardIterator last, const T& val)
{
    while(first != last){
        *first = val;
        ++first;
    }
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

template<class T>
class Print
{
public:
    void operator() (const T& val){
        std::cout<<' '<<val;
    }
};

int main()
{
    std::vector<int> myvector(10);
    std::fill(myvector.begin(), myvector.end(), 1);
    std::for_each(myvector.begin(), myvector.end(), Print<int>());
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
std::fill_n
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val);

Fill sequence with value
Assigns val to the first n elements of the sequence pointed by first.
[将序列中从first开始的n个元素赋值为val]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class OutputIterator, class Size, class T>
OutputIterator fill_n (OutputIterator first, Size n, const T& val)
{
    while(n>0){
        *first = val;
        ++first;    --n;
    }
    return first;    //since C++11
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> myvector(8, 10);
    std::vector<int>::iterator it;

    std::fill_n(myvector.begin(), 4, 20);
    std::fill_n(myvector.begin()+4, 2, 30);

    for(it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class Generator>
void generate (ForwardIterator first, ForwardIterator last);

Generate values for range with function
Assigns the value returned by successive calls to gen to the elements in the range [first,last).
[通过连续调用gen()函数将返回值赋值给[first, last)中的元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class Generator>
void generate(ForwardIterator first, ForwardIterator last)
{
    while(first != last){
        *first = gen();
        ++first;
    }
}
*/

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>        //std::time
#include <cstdlib>    //std::rand, std::srand

// function generator
int RandomNumber() {
    return rand()%100;
}

class UniqueNumber
{
private:
    int current;
public:
    UniqueNumber()    {current = 0;}
    int operator() ()    {return ++current;}
};

int main()
{
    std::vector<int> myvector(10);
    std::vector<int>::iterator it;

    std::generate(myvector.begin(), myvector.end(), RandomNumber);

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    std::generate (myvector.begin(), myvector.end(), UniqueNumber());

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';
    
    system("pause");
    return 0;
}
/*
template <class OutputIterator, class Size, class Generator>
void generate_n (OutputIterator first, Size n, Generator gen);

Generate values for sequence with function
Assigns the value returned by successive calls to gen to the first n elements of the sequence pointed by first.
[通过连续调用gen()函数将返回值赋值给[first, last)中的前n个元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class OutputIterator, class Size, class Generator>
void generate_n ( OutputIterator first, Size n, Generator gen )
{
    while (n>0) {
        *first = gen();
        ++first; --n;
    }
}
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::generate_n

int current = 0;
int UniqueNumber () { return ++current; }

int main () 
{
    int myarray[9];

    std::generate_n (myarray, 9, UniqueNumber);

    std::cout << "myarray contains:";
    for (int i=0; i<9; ++i)
        std::cout << ' ' << myarray[i];
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);

Remove value from range
[Note: This is the reference for algorithm remove. See remove for <cstdio>'s remove.]
[注意:这是算法中的remove()函数,而不是头文件<cstdio>中的remove()函数]
Transforms the range [first,last) into a range with all the elements that compare equal to val removed, and returns an iterator to the new end of that range.
[将[first, last)中值为val的元素移除,并返回一个指向新末尾的迭代器]
The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the elements that compare equal to val by the next element that does not, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.
[该函数不会改变对象的属性(也就是说不会改变数组或者容器的大小):移除操作是通过用下一个不等于val的元素代替等于val的元素,并且返回指向新的末尾的迭代器]
The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.
[没有被移除的元素的相对位置保持不变,但从返回的迭代器到最后一个元素之间的元素处于一种有效但未指定的状态]
The function uses operator== to compare the individual elements to val.
[该函数利用operator==来比较元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
{
    ForwardIterator result = first;
    while(first != last){
        if(!(*first == val)){
            *result = *first;
            ++result;
        }
        ++first;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main () {
    int myints[] = {10, 20, 20, 20, 30, 30, 20, 20, 10};
    std::vector<int> myvector(myints, myints+9);
    std::vector<int>::iterator it, result;

    result = std::remove(myvector.begin(), myvector.end(), 20);

    std::cout << "myvector contains:";
    for (it=myvector.begin(); it != result; ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class UnaryPredicate>
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred);

Remove elements from range
Transforms the range [first,last) into a range with all the elements for which pred returns true removed, and returns an iterator to the new end of that range.
[移除[first, last)中使pred()返回真的元素,并返回新的指向末尾的迭代器]
The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the elements for which pred returns true by the next element for which it does not, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.
[该函数不会改变对象的属性(也就是说不会改变数组或者容器的大小):移除操作是通过用下一个使pred()返回假的元素代替使pred()返回真的元素,并且返回指向新的末尾的迭代器]
The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.
[没有被移除的元素的相对位置保持不变,但从返回的迭代器到最后一个元素之间的元素处于一种有效但未指定的状态]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class UnaryPredicate>
ForwardIterator remove_if (ForwardIterator first, ForwardIterator last, UnaryPredicate pred)
{
    ForwardIterator result = first;
    while(first != last){
        if(!pred(*first)){
            *result = *first;
            ++result;
        }
        ++first;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

bool IsOdd (int i) { return ((i%2)==1); }

int main () 
{
    int myints[] = {1,2,3,4,5,6,7,8,9};            // 1 2 3 4 5 6 7 8 9

    int* pbegin = myints;                         
    int* pend = myints+sizeof(myints)/sizeof(int); 

    pend = std::remove_if (pbegin, pend, IsOdd);   // 2 4 6 8 ? ? ? ? ?

    std::cout << "the range contains:";
    for (int* p=pbegin; p!=pend; ++p)
        std::cout << ' ' << *p;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator, class T>
OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val);

Copy range removing value
Copies the elements in the range [first,last) to the range beginning at result, except those elements that compare equal to val.
[将[first, last)中不等于val的元素拷贝到以result起始的区间中]
The resulting range is shorter than [first,last) by as many elements as matches in the sequence, which are "removed".
[结果区间中的元素加上被移除元素即为原始区间中的元素]
The function uses operator== to compare the individual elements to val.
[该函数使用operator==来判断元素是否为val]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class InputIterator, class OutputIterator, class T>
OutputIterator remove_copy (InputIterator first, InputIterator last, OutputIterator result, const T& val)
{
    while(first != last){
        if(!(*first == val)){
            *result = *first;
            ++result;
        }
        ++first;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main () 
{
    int myints[] = {10,20,30,30,20,10,10,20};               // 10 20 30 30 20 10 10 20
    std::vector<int> myvector (8);

    std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred);

Copy range removing values
Copies the elements in the range [first,last) to the range beginning at result, except those elements for which pred returns true.
[将[first, last)中使pred()返回真的元素拷贝到以result起始的区间中]
The resulting range is shorter than [first,last) by as many elements as matches, which are "removed".
[结果区间中的元素加上被移除元素即为原始区间中的元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator remove_copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred)
{
    while(first != last){
        if(!(pred(*first))){
            *result = *first;
            ++result;
        }
        ++first;
    }
    return result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

bool IsOdd (int i) { return ((i%2)==1); }

int main () 
{
    int myints[] = {1,2,3,4,5,6,7,8,9};
    std::vector<int> myvector (9);

    std::remove_copy_if (myints,myints+9,myvector.begin(),IsOdd);

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator>
ForwardIterator unique (ForwardIterator first, ForwardIterator last);

template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique (ForwardIterator first, ForwardIterator last, BinaryPredicate pred);

Remove consecutive duplicates in range
Removes all but the first element from every consecutive group of equivalent elements in the range [first,last).
[去掉区间[first, last)中的重复元素]
The function cannot alter the properties of the object containing the range of elements (i.e., it cannot alter the size of an array or a container): The removal is done by replacing the duplicate elements by the next element that is not a duplicate, and signaling the new size of the shortened range by returning an iterator to the element that should be considered its new past-the-end element.
[该函数不会改变对象的属性(也就是说不会改变数组或者容器的大小):移除操作是通过用下一个非重复元素代替重复元素,并且返回指向新的末尾的迭代器]
The relative order of the elements not removed is preserved, while the elements between the returned iterator and last are left in a valid but unspecified state.
[没有被移除的元素的相对位置保持不变,但从返回的迭代器到最后一个元素之间的元素处于一种有效但未指定的状态]
The function uses operator== to compare the pairs of elements (or pred, in version (2)).
[该函数利用operator==来比较元素(或者用pre)]
The behavior of this function template is equivalent to:
[该模板函数的行为等价于以下操作:]
template <class ForwarIterator>
ForwarIterator unique (ForwarIterator first, ForwarIterator last)
{
    ForwarIterator result = first;
    while(++first != last){
        if(!(*result == *first))
            *(++result) = *first;
    }
    return ++result;
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

bool myfunction (int i, int j){
    return (i == j);
}

int main()
{
    int myints[] = {10, 20, 20, 20, 30, 30, 20, 20, 10};
    std::vector<int> myvector(myints, myints+9);                 // 10 20 20 20 30 30 20 20 10

    // using default comparison.
    std::vector<int>::iterator it;
    it = std::unique(myvector.begin(), myvector.end());        // 10 20 30 20 10 ?  ?  ?  ?
                                                                                    //                          ^
    myvector.resize(std::distance(myvector.begin(), it));    // 10 20 30 20 10

    // using predicate comparison.
    std::unique(myvector.begin(), myvector.end(), myfunction);    // (no changes)

    std::cout<<"myvector contains:";
    for(it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class InputIterator, class OutputIterator>
OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result);

template <class InputIterator, class OutputIterator, class BinaryPredicate>
OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result, BinaryPredicate pred);

Copy range removing duplicates
Copies the elements in the range [first,last) to the range beginning at result, except consecutive duplicates (elements that compare equal to the element preceding).
[将[first last)中的不连续重复元素拷贝到以result起始的区间中]
Only the first element from every consecutive group of equivalent elements in the range [first,last) is copied.
[对于连续重复元素,只拷贝第一个元素]
The comparison between elements is performed by either applying operator==, or the template parameter pred (for the second version) between them.
[元素的比较是通过operator==进行的或者通过模板参数pred]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class InputIterator, class OutputIterator>
OutputIterator unique_copy (InputIterator first, InputIterator last, OutputIterator result)
{
    if (first==last) return result;

    *result = *first;
    while (++first != last) {
        typename iterator_traits<InputIterator>::value_type val = *first;
        if (!(*result == val))   // or: if (!pred(*result,val)) for version (2)
        *(++result)=val;
    }
    return ++result;
}
*/

#include <iostream>
#include <vector>
#include <algorithm>

bool myfunction (int i, int j) {
    return (i==j);
}

int main () {
    int myints[] = {10,20,20,20,30,30,20,20,10};
    std::vector<int> myvector (9);                            // 0  0  0  0  0  0  0  0  0

    // using default comparison:
    std::vector<int>::iterator it;
    it=std::unique_copy (myints,myints+9,myvector.begin());   // 10 20 30 20 10 0  0  0  0
    //                ^

    std::sort (myvector.begin(),it);                          // 10 10 20 20 30 0  0  0  0
    //                ^

    // using predicate comparison:
    it=std::unique_copy (myvector.begin(), it, myvector.begin(), myfunction);
    // 10 20 30 20 30 0  0  0  0
    //          ^

    myvector.resize( std::distance(myvector.begin(),it) );    // 10 20 30

    // print out content:
    std::cout << "myvector contains:";
    for (it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last);

Reverse range
Reverses the order of the elements in the range [first,last).
[反序[first, last)间的元素]
The function calls iter_swap to swap the elements to their new locations.
[该函数调用iter_swap()来交换元素]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class BidirectionalIterator>
void reverse (BidirectionalIterator first, BidirectionalIterator last)
{
    while((first != last) && (first != --last)){
        std::iter_swap(*first, *last);
        ++first;    
    }
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> myvector;

    for(int i=1; i<10; i++)    myvector.push_back(i);
    
    std::reverse(myvector.begin(), myvector.end());

    std::cout<<"myvector contains:";
    for(std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<' '<<*it;
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class BidirectionalIterator, class OutputIterator>
OutputIterator reverse_copy (BidirectionalIterator first, BidirectionalIterator last, OutputIterator result);

Copy range reversed
Copies the elements in the range [first,last) to the range beginning at result, but in reverse order.
[将[first, last)中的元素拷贝到以result起始的区间中,并反转排序]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]

template <class BidirectionalIterator, class OutputIterator>
OutputIterator reverse_copy (BidirectionalIterator first, BidirectionalIterator last, OutputIterator result)
{
    while(first != last){
        --last;
        *result = *last;
        ++result;
    }
    return result;
}
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::reverse_copy
#include <vector>       // std::vector

int main () 
{
    int myints[] ={1,2,3,4,5,6,7,8,9};
    std::vector<int> myvector;

    myvector.resize(9);    // allocate space

    std::reverse_copy (myints, myints+9, myvector.begin());

    // print out content:
    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator>
void rotate (ForwardIterator first, ForwardIterator middle, ForwardIterator last);

Rotate left the elements in range
[将区间中的元素向左旋转]
Rotates the order of the elements in the range [first,last), in such a way that the element pointed by middle becomes the new first element.
[把区间[middle, last)之间的元素向左旋转,使得指向middle的元素成为新的first元素]]
The behavior of this function template (C++98) is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator>
void rotate (ForwardIterator first, ForwardIterator middle, ForwardIterator last)
{
    ForwardIterator next = middle;
    while(first != next){
        swap(*first++, *next++);
        if(next == last)    next = middle;
        else if(first == middle)    middle = next;
    }
}
*/

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    std::vector<int> myvector;
    std::vector<int>::iterator it;

    for(int i=1; i<10; i++)    myvector.push_back(i);    // 1 2 3 4 5 6 7 8 9

    std::rotate(myvector.begin(), myvector.begin()+3, myvector.end());    //4 5 6 7 8 9 1 2 3

    std::cout<<"After rotating, myvector contains: ";
    for(it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<*it<<' ';
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
template <class ForwardIterator, class OutputIterator>
OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result);

Copy range rotated left
Copies the elements in the range [first,last) to the range beginning at result, but rotating the order of the elements in such a way that the element pointed by middle becomes the first element in the resulting range.
[将[first, last)中的元素拷贝到以result起始的区间中,并把区间[middle, last)之间的元素向左旋转,使得指向middle的元素成为第一个元素]]
The behavior of this function template is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class ForwardIterator, class OutputIterator>
OutputIterator rotate_copy (ForwardIterator first, ForwardIterator middle, ForwardIterator last, OutputIterator result)
{
    result=std::copy (middle,last,result);
    return std::copy (first,middle,result);
}
*/

#include <iostream>     // std::cout
#include <algorithm>    // std::reverse_copy
#include <vector>       // std::vector

int main () {
    int myints[] = {10,20,30,40,50,60,70};

    std::vector<int> myvector (7);

    std::rotate_copy(myints,myints+3,myints+7,myvector.begin());

    std::cout << "myvector contains:";
    for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
        std::cout << ' ' << *it;
    std::cout << '\n';

    system("pause");
    return 0;
}
/*
template <class RandomAccessIterator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last);

template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen);

Randomly rearrange elements in range
Rearranges the elements in the range [first,last) randomly.
[重新随机排列[first, last)之间的元素]
The function swaps the value of each element with that of some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness.
[该函数将区间中的每个元素与随机选择的元素交换,如果提供了随机数生成器gen,则由函数gen来决定被选择每一次交换的元素,如果没有提供gen,则该函数使用为指定的随机源]
The behavior of this function template (2) is equivalent to:
[该函数模板的行为等价于以下操作:]
template <class RandomAccessIterator, class RandomNumberGenerator>
void random_shuffle (RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator& gen)
{
     iterator_traits<RandomAccessIterator>::difference_type i, n;
     n = (last-first);
     for(i=n-1; i>0; --i){
         swap(first[i], first[gen(i+1)]);
     }
}
*/

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>

int myrandom(int i){
    int temp = i;
    return std::rand()%i;
}

int main()
{
    std::srand((unsigned)std::time(NULL));
    std::vector<int> myvector;
    std::vector<int>::iterator it;

    for(int i=1; i<10; ++i)    myvector.push_back(i);

    // using built-in random generator.
    std::random_shuffle(myvector.begin(), myvector.end());

    for(it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<*it<<' ';
    std::cout<<'\n';

    // using myrandom.
    std::random_shuffle(myvector.begin(), myvector.end(), myrandom);

    for(it = myvector.begin(); it != myvector.end(); ++it)
        std::cout<<*it<<' ';
    std::cout<<'\n';

    system("pause");
    return 0;
}
/*
int rand (void);

Generate random number
[生成随机数]
Returns a pseudo-random integral number in the range between 0 and RAND_MAX.
[在0-RAND_MAX之间产生一个伪随机整数]
This number is generated by an algorithm that returns a sequence of apparently non-related numbers each time it is called. This algorithm uses a seed to generate the series, which should be initialized to some distinctive value using function srand.
[伪随机数是通过一个算法生成的,每次调用该算法时,该算法都会利用一个种子来产生一系列明显不相关的数,种子需要通过srand()函数来初始化为不同值]
RAND_MAX is a constant defined in <cstdlib>.
[RAND_MAX是一个定义在头文件<cstdlid>中的常量]
A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:
[利用rand()函数在一个已确定的区间中产生伪随机数一个典型做法是将返回值对区间取模并加上区间的初始值,比如:]
v1 = rand() % 100;                // v1 in the range 0 to 99
v2 = rand() % 100 + 1;            // v2 in the range 1 to 100
v3 = rand() % 30 + 1985;        // v3 in the range 1985-2014 
Notice though that this modulo operation does not generate uniformly distributed random numbers in the span (since in most cases this operation makes lower numbers slightly more likely).
[需要注意的是,这种取模操作生成的伪随机数在区间中不是均匀分布的(在大多数情况下,该操作产生值小的数比产生值大的数的概率稍微大一些)]
C++ supports a wide range of powerful tools to generate random and pseudo-random numbers (see <random> for more info).
[C++支持大量的强有力的工具来生成随机数和伪随机数(请参见<random>)]

RAND_MAX
Maximum value returned by rand
[rand()函数的最大返回值]
This macro expands to an integral constant expression whose value is the maximum value returned by the rand function.
[该宏是一个整型常量表达式,表示rand()函数的最大返回值]
This value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation.
[该宏的取值由库决定,但任何库实现都必须保证其值至少为32767]

void srand (unsigned int seed);

Initialize random number generator
[初始化随机数生成器]
The pseudo-random number generator is initialized using the argument passed as seed.
[srand()函数将传递进来的参数seed作为种子,初始化伪随机数生成器]
For every different seed value used in a call to srand, the pseudo-random number generator can be expected to generate a different succession of results in the subsequent calls to rand.
[每次调用srand()函数时,如果传递进来的seed不同,则随后调用rand()时,伪随机数生成器应该生成一系列不同的结果]
Two different initializations with the same seed will generate the same succession of results in subsequent calls to rand.
[如果调用srand()函数时,传递的seed相同,则随后调用rand()时,伪随机数生成器生成的结果将是相同的]
If seed is set to 1, the generator is reinitialized to its initial value and produces the same values as before any call to rand or srand.
[如果seed是1,则生成器被重置为初始值]
In order to generate random-like numbers, srand is usually initialized to some distinctive runtime value, like the value returned by function time (declared in header <ctime>). This is distinctive enough for most trivial randomization needs.
[为了生成看起来像是随机数的数据,srand()的seed通常使用被初始化为不同的运行时间值,比如time()函数的返回值,这样能够充分保证大多数简单的随机需求]
*/

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
    std::cout<<"First number: "<<rand()%100<<'\n';
    srand(time(NULL));
    std::cout<<"Random number: "<<rand()%100<<'\n';
    srand(1);
    std::cout<<"Again the first number: "<<rand()%100<<'\n';

    system("pause");
    return 0;
}                                                                                                           
posted @ 2015-07-13 19:12  codeplayplus  阅读(415)  评论(0编辑  收藏  举报