C++相关闲碎记录(6)

1、使用shared_ptr

cpp 复制代码
#include <iostream>
#include <memory>
#include <set>
#include <deque>
#include <algorithm>
#include <string>

class Item {
private:
    std::string name;
    float price;
public:
    Item(const std::string& n, float p = 0) :name(n), price(p) {}
    std::string getName() const {
        return name;
    }
    void setName(const std::string& n) {
        name = n;
    }
    float getPrice() const {
        return price;
    }
    float setPrice(float p) {
        price = p;
        return p;
    }
};

template <typename Coll>
void printItems(const std::string& msg, const Coll& coll) {
    std::cout << msg << std::endl;
    for (const auto& elem: coll) {
        std::cout << " " << elem->getName() << ": " << elem->getPrice() << std::endl;
    }
}

int main() {
    using namespace std;
    typedef shared_ptr<Item> ItemPtr;
    set<ItemPtr> allItems;
    deque<ItemPtr> bestsellers;

    bestsellers = {ItemPtr(new Item("Kong Yize", 20.10)),
                   ItemPtr(new Item("A Midsummer Night's Dream", 14.99)),
                   ItemPtr(new Item("The Maltese Falcon", 9.88))};
    allItems = {ItemPtr(new Item("Water", 0.44)),
                ItemPtr(new Item("Pizza", 2.22))};
    allItems.insert(bestsellers.begin(), bestsellers.end());
    printItems("bestsellers: ", bestsellers);
    printItems("all: ", allItems);
    cout << endl;

    for_each(bestsellers.begin(), bestsellers.end(),
             [](shared_ptr<Item>& elem) {
                elem->setPrice(elem->getPrice() * 2);
             });
    
    bestsellers[1] = *(find_if(allItems.begin(), allItems.end(),
                       [](shared_ptr<Item> elem) {
                            return elem->getName() == "Pizza";
                       }));
    bestsellers[0]->setPrice(44.88);
    printItems("bestsellers: ", bestsellers);
    printItems("all: ", allItems);
    return 0;
}

面的set使用find的时候,会找出拥有相等value的元素,现在却比较的是内部的指针,

allItems.find(ItemPtr(new Item("Pizza", 2.22))) //can't be successful,所以这里必须使用find_if算法。

2、advance

cpp 复制代码
#include <iterator>
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

int main()
{
    list<int> coll;

    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }

    list<int>::iterator pos = coll.begin();

    // print actual element
    cout << *pos << endl;

    // step three elements forward
    advance (pos, 3);

    // print actual element
    cout << *pos << endl;

    // step one element backward
    advance (pos, -1);

    // print actual element
    cout << *pos << endl;
}
输出:
1
4
3

3、iter_swap()

交换迭代器的值,迭代器类型不必相同,所指的两个值必须可以相互赋值。

cpp 复制代码
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
#include "print.hpp"
using namespace std;

int main()
{
    list<int> coll;

    // insert elements from 1 to 9
    for (int i=1; i<=9; ++i) {
        coll.push_back(i);
    }

    PRINT_ELEMENTS(coll);

    // swap first and second value
    iter_swap (coll.begin(), next(coll.begin()));

    PRINT_ELEMENTS(coll);

    // swap first and last value
    iter_swap (coll.begin(), prev(coll.end()));

    PRINT_ELEMENTS(coll);
}
输出:
1 2 3 4 5 6 7 8 9 
2 1 3 4 5 6 7 8 9
9 1 3 4 5 6 7 8 2
cpp 复制代码
#include <iterator>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    // create list with elements from 1 to 9
    vector<int> coll = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // find position of element with value 5
    vector<int>::const_iterator pos;
    pos = find (coll.cbegin(), coll.cend(),
                5);

    // print value to which iterator pos refers
    cout << "pos:  " << *pos << endl;

    // convert iterator to reverse iterator rpos
    vector<int>::const_reverse_iterator rpos(pos);

    // print value to which reverse iterator rpos refers
    cout << "rpos: " << *rpos << endl;
}
输出:
pos:  5
rpos: 4
cpp 复制代码
#include <iterator>
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;

void print (int elem)
{
    cout << elem << ' ';
}

int main()
{
    // create deque with elements from 1 to 9
    deque<int> coll = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // find position of element with value 2
    deque<int>::const_iterator pos1;
    pos1 = find (coll.cbegin(), coll.cend(),  // range
                 2);                          // value

    // find position of element with value 7
    deque<int>::const_iterator pos2;
    pos2 = find (coll.cbegin(), coll.cend(),  // range
                 7);                          // value

    // print all elements in range [pos1,pos2)
    for_each (pos1, pos2,     // range
              print);         // operation
    cout << endl;

    // convert iterators to reverse iterators
    deque<int>::const_reverse_iterator rpos1(pos1);
    deque<int>::const_reverse_iterator rpos2(pos2);

    // print all elements in range [pos1,pos2) in reverse order
    for_each (rpos2, rpos1,   // range
              print);         // operation
    cout << endl;
}
输出:
2 3 4 5 6 
6 5 4 3 2

4、使用base()将reverse迭代器转回正常

cpp 复制代码
#include <iterator>
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

int main()
{
    // create list with elements from 1 to 9
    list<int> coll = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    // find position of element with value 5
    list<int>::const_iterator pos;
    pos = find (coll.cbegin(), coll.cend(),  // range
                5);                          // value

    // print value of the element
    cout << "pos:   " << *pos << endl;

    // convert iterator to reverse iterator
    list<int>::const_reverse_iterator rpos(pos);

    // print value of the element to which the reverse iterator refers
    cout << "rpos:  " << *rpos << endl;

    // convert reverse iterator back to normal iterator
    list<int>::const_iterator rrpos;
    rrpos = rpos.base();

    // print value of the element to which the normal iterator refers
    cout << "rrpos: " << *rrpos << endl;
}
输出:
pos:   5
rpos:  4
rrpos: 5

5、back_inserter

cpp 复制代码
#include <vector>
#include <algorithm>
#include <iterator>
#include "print.hpp"

using namespace std;

int main() {
    vector<int> coll;
    back_insert_iterator<vector<int>> iter(coll);

    *iter = 1;
    *iter++;
    *iter = 2;
    iter++;
    *iter = 3;
    PRINT_ELEMENTS(coll);

    // convenient way
    back_inserter(coll) = 44;
    back_inserter(coll) = 55;
    PRINT_ELEMENTS(coll);

    // use back inserter to append all elements again
    // - reserve enough memory to avoid reallocation
    coll.reserve(2*coll.size());
    copy(coll.begin(), coll.end(), back_inserter(coll));
    PRINT_ELEMENTS(coll);
    return 0;
}
输出:
1 2 3 
1 2 3 44 55
1 2 3 44 55 1 2 3 44 55

6、front_inserter

cpp 复制代码
#include <list>
#include <algorithm>
#include <iterator>
#include "print.hpp"

using namespace std;

int main() {
    list<int> coll;
    front_insert_iterator<list<int>> iter(coll);

    *iter = 1;
    iter++;
    *iter = 2;
    iter++;
    *iter = 3;

    PRINT_ELEMENTS(coll);

    front_inserter(coll) = 44;
    front_inserter(coll) = 55;

    PRINT_ELEMENTS(coll);
    copy(coll.begin(), coll.end(), front_inserter(coll));
    PRINT_ELEMENTS(coll);
    return 0;
}
输出:
3 2 1 
55 44 3 2 1
1 2 3 44 55 55 44 3 2 1

7、inserter

cpp 复制代码
#include <set>
#include <list>
#include <algorithm>
#include <iterator>
#include "print.hpp"

using namespace std;

int main() {
    set<int> coll;
    insert_iterator<set<int>> iter(coll, coll.begin());
    *iter = 1;
    iter++;
    *iter = 2;
    iter++;
    *iter = 3;

    PRINT_ELEMENTS(coll,"set: ");
    inserter(coll, coll.end()) = 44;
    inserter(coll, coll.end()) = 55;
    PRINT_ELEMENTS(coll, "set: ");

    list<int> coll2;
    copy(coll.begin(), coll.end(), inserter(coll2, coll2.begin()));

    PRINT_ELEMENTS(coll2, "list: ");
    copy(coll.begin(), coll.end(), inserter(coll2, ++coll2.begin()));
    PRINT_ELEMENTS(coll2, "list: ");
    return 0;
}
输出:
set: 1 2 3 
set: 1 2 3 44 55
list: 1 2 3 44 55
list: 1 1 2 3 44 55 2 3 44 55

8、ostream迭代器

cpp 复制代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

using namespace std;

int main() {
    ostream_iterator<int> intWriter(cout, "\n");
    *intWriter = 43;
    intWriter++;
    *intWriter = 77;
    intWriter++;
    *intWriter = -5;

    vector<int> coll = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    copy(coll.begin(), coll.end(), ostream_iterator<int>(cout));
    cout << endl;
    copy(coll.begin(), coll.end(), ostream_iterator<int>(cout, " < "));
    cout << endl;
    return 0;
}
输出:
43
77
-5
123456789
1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 <

9、istream迭代器

cpp 复制代码
#include <iterator>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {
    istream_iterator<string> cinPos(cin);
    ostream_iterator<string> coutPos(cout, " ");

    while (cinPos != istream_iterator<string>()) {
        advance(cinPos, 2);
        if (cinPos != istream_iterator<string>()) {
            *coutPos++ = *cinPos++;
        }
    }
    cout << endl;
    return 0;
}
输入:
No one objects if you are doing
a good programming job for 
someone whom you respect
输出:
objects are good for you

10、move迭代器

cpp 复制代码
std::vector<string> v2(make_move_iterator(s.begin()),
                       make_move_iterator(s.end()));
相关推荐
唐诺16 分钟前
几种广泛使用的 C++ 编译器
c++·编译器
冷眼看人间恩怨1 小时前
【Qt笔记】QDockWidget控件详解
c++·笔记·qt·qdockwidget
红龙创客1 小时前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
Lenyiin1 小时前
第146场双周赛:统计符合条件长度为3的子数组数目、统计异或值为给定值的路径数目、判断网格图能否被切割成块、唯一中间众数子序列 Ⅰ
c++·算法·leetcode·周赛·lenyiin
yuanbenshidiaos3 小时前
c++---------数据类型
java·jvm·c++
十年一梦实验室3 小时前
【C++】sophus : sim_details.hpp 实现了矩阵函数 W、其导数,以及其逆 (十七)
开发语言·c++·线性代数·矩阵
taoyong0014 小时前
代码随想录算法训练营第十一天-239.滑动窗口最大值
c++·算法
这是我584 小时前
C++打小怪游戏
c++·其他·游戏·visual studio·小怪·大型·怪物
fpcc4 小时前
跟我学c++中级篇——C++中的缓存利用
c++·缓存
呆萌很4 小时前
C++ 集合 list 使用
c++