getting a range from a vector

Hi,
I apologize if this is too basic a quesiton.

I have a vector<Date> where Date is a class representing a Date. Dates are inserted into the vector in ascending order.

1. I want to get a vector of all the dates upto and including a given date. If the given date is not there, I want to dates upto the given date.

2. I want to provide a begin and end dates. I want to get all the dates in that range. Begin and end dates may not necessarity in the intial vector.

How do I do that. I was looking at find algorithm, but couldn't quite figure out how to do that.

Any help is really appreciated. Many thanks.

John
You want the upper_bound and lower_bound algorithms.

To copy out a subvector, use a back_insert_iterator:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <algorithm>
#include <iterator>
...
#include <vector>
using namespace std;

class Date
  {
  ...
  bool operator < ( const Date& that )
    {
    // return true if (*this < that)
    }
  };

vector <Date> all_dates;
vector <Date> some_dates;

copy(
  lower_bound( all_dates.begin(), all_dates.end(), Date( '2007-2-10' ) ),
  upper_bound( all_dates.begin(), all_dates.end(), Date( '2008-4-28' ) ),
  back_inserter( some_dates )
  );

// now some_dates lists all dates from 2007-2-10 to 2008-4-28, inclusive 


Hope this helps.
thank you very much.

John
Glad to have helped.

BTW, a lot of people are scared of the STL and would not have considered this a basic question.

It has limits and it sure is obnoxious and frustrating when you hit them but often you just need to stare at it a bit and think sideways.

:-]
Thanks much for the encouragement. Knowing there are a very nice people like yourself out there who are ready to help is a big relief for beginners like myself.

Thanks again.

John
Topic archived. No new replies allowed.