PQ使用

priority_queue默认用 < 比较元素,也就是数值大的优先级排列在最前面,最先出队列。那么怎样使它翻转输出呢,书中的例子只是简单的吧key本身的大小作为优先级来使用了,那么这里就要借助一个结构了,用来存储key和priority
第一次代码比较复杂:
pq.cpp

#include<cstdio>
#include<queue>

using namespace std;

class NODE {
    public:
        char ch;
        int  freq;

        bool operator>(const NODE n1) const
        {
            return (this->freq > n1.freq);
        }

        NODE(char c, int n)
        {
            ch = c;
            freq = n;
        }
};

int main()
{
    priority_queue< NODE, vector<NODE>, greater<NODE> > pq;

    pq.push(NODE('a', 8));
    pq.push(NODE('b', 4));
    pq.push(NODE('c', 5));

    printf("%d %c\n", pq.top().freq, pq.top().ch);
    pq.pop();
    printf("%d %c\n", pq.top().freq, pq.top().ch);

    return 0;
}

第二次简单了一些,pq_v2.cpp:

#include<cstdio>
#include<queue>

using namespace std;

class NODE {
    public:
        char ch;
        int  freq;

        // cos the default priority is from biger one to smaller one
        bool operator<(const NODE n1) const
        {
            return (this->freq > n1.freq);// priority retorate.
        }

        NODE(char c, int n)
        {
            ch = c;
            freq = n;
        }
};

int main()
{
    priority_queue<NODE> pq;

    pq.push(NODE('a', 8));
    pq.push(NODE('b', 4));
    pq.push(NODE('c', 5));

    printf("%d %c\n", pq.top().freq, pq.top().ch);
    pq.pop();
    printf("%d %c\n", pq.top().freq, pq.top().ch);

    return 0;
}


这里用的是模板库提供的pq的模板,它的定义时这个样子的:

In their implementation in the C++ Standard Template Library, priority queues take three template parameters:

1
2
template < class T, class Container = vector<T>,
           class Compare = less<typename Container::value_type> > class priority_queue;

Where the template parameters have the following meanings:
  • T: Type of the elements.
  • Container: Type of the underlying container object used to store and access the elements.
  • Compare: Comparison class: A class such that the expression comp(a,b), where comp is an object of this class and aand b are elements of the container, returns true if a is to be placed earlier than b in a strict weak ordering operation. This can either be a class implementing a function call operator or a pointer to a function. This defaults to less<T>, which returns the same as applying the less-than operator (a<b).
    The priority_queue object uses this expression when an element is inserted or removed from it (using push orpop, respectively) to grant that the element popped is always the greatest in the priority queue.
In the reference for the  priority_queue  member functions, these same names ( T Container  and  Compare ) are assumed for the template parameters.

默认的话只需要提供数据的类型即可,对于基本的数据类型,他是按照less的顺序入队列,出队列的时候是优先级比较大的先出;它默认使用的容器是vector;然后还有less实际上是一个函数对象,它的内部重载了()操作符,相当于一个<号,这里贴出greater的代码理解一下,

This class is derived from  binary_function  and is defined as:

1
2
3
4
template <class T> struct greater : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const
    {return x>y;}
};

Members

bool operator() (const T& x, const T& y)
Member function returning the result of the comparison  x>y.
可以看到他是比较了x, y的大小,所以对于我们自己提供的类型,也要重载>或者<运算符就可以了,这也就是2中的重载的作用。


bool operator<(const NODE n1)后面少了一个const,以下是G++出错的提示,一满屏了快。。。:

xi@xi-virtual-machine:1053$ g++ huffman.cpp -o huffman
In file included from /usr/include/c++/4.6/queue:64:0,
                 from huffman.cpp:2:
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp = Item]’:
/usr/include/c++/4.6/bits/stl_heap.h:305:4:   instantiated from ‘void std::__adjust_heap(_RandomAccessIterator, _Distance, _Distance, _Tp, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Item*, std::vector<Item, std::allocator<Item> > >, _Distance = int, _Tp = Item, _Compare = std::less<Item>]’
/usr/include/c++/4.6/bits/stl_heap.h:436:4:   instantiated from ‘void std::make_heap(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<Item*, std::vector<Item, std::allocator<Item> > >, _Compare = std::less<Item>]’
/usr/include/c++/4.6/bits/stl_queue.h:391:9:   instantiated from ‘std::priority_queue<_Tp, _Sequence, _Compare>::priority_queue(const _Compare&, const _Sequence&) [with _Tp = Item, _Sequence = std::vector<Item, std::allocator<Item> >, _Compare = std::less<Item>]’
huffman.cpp:31:26:   instantiated from here
/usr/include/c++/4.6/bits/stl_function.h:236:22: error: passing ‘const Item’ as ‘this’ argument of ‘bool Item::operator<(Item)’ discards qualifiers [-fpermissive]


### Python 爬虫 PyQuery 使用教程 #### 安装 PyQuery 为了使用 PyQuery 进行网页抓取,首先需要安装该库。可以通过 pip 工具轻松完成这一过程。 ```bash pip install pyquery ``` #### 初始化 PyQuery 对象 PyQuery 支持多种方式来加载 HTML 数据源: - **传入字符串** 可以直接向 PyQuery 构造函数传递一段 HTML 字符串[^3]。 ```python from pyquery import PyQuery as pq doc = pq('<html><body><h1>Hello, world!</h1></body></html>') ``` - **传入文件路径** 如果本地保存了一份 HTML 文件,则可以直接通过文件路径读取。 ```python doc = pq(filename='example.html') ``` - **传入 URL 地址** 当然也支持直接从网络获取页面内容并解析。 ```python url = 'http://example.com' doc = pq(url=url) ``` #### 获取与操作元素 一旦有了 PyQuery 实例 `doc` 后,就可以像 jQuery 那样方便地选取节点了。 ##### 查找单个元素 对于简单的选择器表达式来说,只需调用 `.find()` 方法即可找到匹配的第一个元素。 ```python title = doc('title').text() print(title) # 输出<title>标签内的文本内容 ``` ##### 多个同级元素的选择 当遇到多个相同的兄弟节点时,可通过索引来访问特定的一个。 ```python items = doc('.item') # 所有 class="item" 的元素列表 for i in range(len(items)): item_text = items.eq(i).text() # eq(n): 返回第 n+1 项 print(f'Item {i}:', item_text) ``` ##### 属性和文本提取 除了能够获得整个 DOM 节点外,还可以单独取出其内部的文字或是属性值。 ```python link_href = doc('a:first').attr.href # 提取第一个<a>链接的 href 属性 img_src = doc('img:last').attr.src # 抓取最后一个<img>图片 src 属性 paragraph_content = doc('#content p').text() # id=content 下面<p>的内容 ``` ##### CSS 伪类选择器的支持 得益于底层强大的 lxml 解析引擎,PyQuery 不仅限于标准的选择语法,还兼容一些常见的 CSS 伪类写法。 ```python active_links = doc(':not(.disabled)').filter('a.active') # 排除 .disabled 类型之外的所有激活状态 a 标签 first_child_divs = doc('> div:first-child') # 直接子代中的首个 <div> last_paragraphs = doc('p:last-of-type') # 每组最后一个小节 ``` #### 浏览器模拟与动态加载处理 虽然 PyQuery 主要针对静态 HTML 页面的操作,但在面对 JavaScript 渲染后的复杂场景下,通常会结合 Selenium 或 Puppeteer 等工具先执行渲染动作再交由 PyQuery 分析最终结果[^2]。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值