eXile 的专栏

vector的有序化操作

  在有些情况下,需要用到一个有序的vector。它的有序操作有三种:查找,插入,删除。
  
  插入实现:
template <typename Container>
inline void ordered_insert(Container
& c,  typename Container::value_type const& t)
{
    c.insert(std::upper_bound(c.begin(), c.end(), t), t);
}

template 
<typename Container, typename Cmp>
inline void ordered_insert(Container
& c, typename Container::value_type const& t, Cmp cmp)
{
    c.insert(std::upper_bound(c.begin(), c.end(), t, cmp), t);
}
  
  删除实现:
template <typename Container, typename It>
inline void erase_range(Container
& c, std::pair<It, It> const& r)
{
    c.erase(r.first, r.second);
}

template 
<typename Container>
inline void ordered_erase(Container
& c,  typename Container::value_type const& t)
{
    erase_range(c, std::equal_range(c.begin(), c.end(), t));
}

template 
<typename Container, typename T, typename Cmp>
inline void ordered_erase(Container
& c, T const& t, Cmp cmp)
{
    erase_range(c, std::equal_range(c.begin(), c.end(), t, cmp));
}

  查找可通过binary_search, lower_bound, upper_bound, 或者equal_range实现。如果要实现类似map的关键字搜索,有一个技巧,就是用比较函数进行重载,比如学生要按学号查找,则用以下定义:
struct Student
{
    
int            id;
    std::
string name;

    struct LessThan
    {
        bool operator() (Student 
const& x, Student const& y)
        {
            return x.id 
< y.id;
        }

        bool operator() (Student 
const& x, int id)
        {
            return x.id 
< id;
        }

        bool operator() (
int id, Student const& y)
        {
            return id 
< y.id;
        }
    };
};

查找学号为5的学生:
std::vector<Student> students;

bool exist = std::binary_search(students.begin(), students.end(), 5, Student::LessThan());

删除学号为5的学生:
ordered_erase(students, 5, Student::LessThan());

posted on 2008-01-29 13:13 eXile 阅读(3943) 评论(1)  编辑 收藏 引用 所属分类: C/C++代码片段STL/BOOST

评论

# re: vector的有序化操作 2008-01-30 09:08 FongLuo

好文,好文~~  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2008年1月>
303112345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

常用链接

留言簿(18)

随笔分类

随笔档案

服务器编程

搜索

最新评论

阅读排行榜

评论排行榜