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()));
相关推荐
醉颜凉23 分钟前
【NOIP提高组】潜伏者
java·c语言·开发语言·c++·算法
hunandede30 分钟前
FFmpeg 4.3 音视频-多路H265监控录放C++开发十三.2:avpacket中包含多个 NALU如何解析头部分析
c++·ffmpeg·音视频
爱学习的大牛1231 小时前
通过vmware虚拟机安装和调试编译好的 ReactOS
c++·windows内核
tumu_C2 小时前
C++模板特化实战:在使用开源库boost::geometry::index::rtree时,用特化来让其支持自己的数据类型
c++·开源
杜若南星2 小时前
保研考研机试攻略(满分篇):第二章——满分之路上(1)
数据结构·c++·经验分享·笔记·考研·算法·贪心算法
Neophyte06083 小时前
C++算法练习-day40——617.合并二叉树
开发语言·c++·算法
云空3 小时前
《InsCode AI IDE:编程新时代的引领者》
java·javascript·c++·ide·人工智能·python·php
写bug的小屁孩3 小时前
websocket初始化
服务器·开发语言·网络·c++·websocket·网络协议·qt creator
湖南罗泽南3 小时前
Windows C++ TCP/IP 两台电脑上互相传输字符串数据
c++·windows·tcp/ip
可均可可4 小时前
C++之OpenCV入门到提高005:005 图像操作
c++·图像处理·opencv·图像操作