list中如何查找两个元素间的某个元素

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

int main()
{
    list<int> coll;
    list<int>::iterator pos;

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

    /* find position of element with value 3
     * - there is none, so pos gets coll.end()
     */
    pos = find (coll.begin(), coll.end(),    // range
                3);                          // value
    
    /* reverse the order of elements between found element and the end
     * - because pos is coll.end() it reverses an empty range
     */
    reverse (pos, coll.end());

    // find positions of values 25 and 35
    list<int>::iterator pos25, pos35;
    pos25 = find (coll.begin(), coll.end(),  // range
                  25);                       // value
    pos35 = find (coll.begin(), coll.end(),  // range
                  35);                       // value

    /* print the maximum of the corresponding range
     * - note: including pos25 but excluding pos35
     */
    cout << "max: " << *max_element (pos25, pos35) << endl;

    // process the elements including the last position
    cout << "max: " << *max_element (pos25, ++pos35) << endl;
}

以上程序,数字按照顺序插入到链表之中,因此,pos25在pos35前,程序可正常运行。

如果随机插入这些数字,则执行*max_element (pos25, pos35)可能会导致未定义的行为,因为pos25可能在pos35之后。


解决方法1:

如果使用的是vector容器,vector容器的迭代器为随机迭代器,可以使用operator<进行比较。

	if (pos25 < pos35) {
		max_element(pos25, pos35);
	}
	else if (pos 35 < pos25) {
		max_element(pos35, pos25);
	}
	else {
		// itr equal
	}

解决方法2:

分段查找,先找到一个迭代器,以这个迭代器分界,分别在起点到这个迭代器,这个迭代器到终点进行查找另一个迭代器。代码如下:

	pos25 = find(coll.begin(), coll.end(), 25);
	pos35 = find(coll.begin(), pos25, 35);
	if (pos35 != pos25) {
		// pos35在pos25前
		max_element(pos35, pos25);
	}
	else {
		pos35 = find(pos25, coll.end(), 35);
		if (pos35 != pos25) {
			// pos25在pos35前
			max_element(pos25, pos35);
		}
	}
	else {
		// itr equal, 没有找pos35
	}

解决方案3:

	pos = find_if (coll.begin(), coll.end(),
					compose_f_gx_hx(logical_or<bool(),
									bind2nd(equal_to<int>(), 25),
									bind2nd(equal_to<int>(), 35)));

pos 为等于25或35的第一个迭代器。然后在pos和end之间查找另一个迭代器。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值