Exemple #1
0
void Ex9_26()
{
    std::cout << "Exercise 9.26:" << std::endl;

    int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
    std::vector<int> ivec(ia, ia + sizeof ia / sizeof ia[0]);
    std::list<int> ilst(std::begin(ia), std::end(ia)); // C++11

    auto it1 = ilst.begin();
    while (it1 != ilst.end()) {
        if (*it1 % 2 != 0) // odd
            it1 = ilst.erase(it1);
        else
            ++it1;
    }

    auto it2 = ivec.begin();
    while (it2 != ivec.end()) {
        if (*it2 % 2 == 0) // even
            it2 = ivec.erase(it2);
        else
            ++it2;
    }

    std::cout << "ivec: ";
    for (auto it = ivec.cbegin(); it != ivec.cend(); ++it)
        std::cout << *it << " ";

    std::cout << "\nilst: ";
    for (auto it = ilst.cbegin(); it != ilst.cend(); ++it)
        std::cout << *it << " ";
    std::cout << std::endl;
}
int main()
{
// Sequence creation
    std::vector<int> ilvec = initialize<int>();
    std::vector<int> ivec(ilvec.cbegin(), ilvec.cend());

    constexpr int arr_sz(11);
    ilvec = initialize<int>(arr_sz);
    std::array<int, arr_sz> ilarr({1,2,3,4,5,6,7,8,9,50,61});

    ilvec = initialize<int>();
    std::list<int> ilst(ilvec.cbegin(), ilvec.cend());

    ilvec = initialize<int>();
    std::forward_list<int> iflst(ilvec.cbegin(), ilvec.cend());

    ilvec = initialize<int>();
    std::deque<int> ideq(ilvec.cbegin(), ilvec.cend());

    int iarr[]{1, 2, 3, 6, 5, 4, 3, 44, 5, 232, 45, 76, 654, 96, 687, 4, 65, 89,343, 23};

// Print
    print(ivec, "ivec");
    print(ilarr, "ilarr");
    print(ilst, "ilst");
    print(iflst, "iflst");
    print(ideq, "ideq");
    print(iarr, "iarr");

// Use algorithms
    int val1 = 85, val2 = 54;
    std::cout << "sum = " << std::accumulate(ivec.cbegin(), ivec.cend(), 0) << std::endl;
    std::cout << "difference = " << std::accumulate(ideq.cbegin(), ideq.cend(), 10, diff<int>) << std::endl;
    std::cout << "inner product = " << std::inner_product(ilarr.cbegin(), ilarr.cend(),ilst.cbegin(), 0) << std::endl;
    std::cout << "custom inner product = " << std::inner_product(iflst.cbegin(), iflst.cend(), std::begin(iarr), 777, mod<int>, diff<int>) << std::endl;

    std::vector<int> cpy(ilst.size()), cpy1(ivec.size());
    std::partial_sum(ilst.cbegin(), ilst.cend(), cpy.begin());
    print(cpy, "cpy");

    std::partial_sum(ivec.cbegin(), ivec.cend(), cpy1.begin(), diff<int>);
    print(cpy1, "cpy1");

    std::vector<int> cpy2(arr_sz), cpy3(20);
    std::adjacent_difference(ilarr.cbegin(), ilarr.cend(), cpy2.begin());
    print(cpy2, "cpy2");

    std::adjacent_difference(std::begin(iarr), std::end(iarr), cpy3.begin(), mod<int>);
    print(cpy3, "cpy3");

    print(iflst, "iflst");
    std::iota(iflst.begin(), iflst.end(), val1);
    print(iflst, "iflst");

    return 0;
}