在有些情況下,需要用到一個有序的vector。它的有序操作有三種:查找,插入,刪除。
插入實現(xiàn):
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);
}

刪除實現(xiàn):
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實現(xiàn)。如果要實現(xiàn)類似map的關(guān)鍵字搜索,有一個技巧,就是用比較函數(shù)進行重載,比如學生要按學號查找,則用以下定義:
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());