开发者

C++ less verbose alternative to passing container.start() and container.end()

I declare a vector<Bla> blaVec and write a function:

template<typename Iterator>
void doSomething(Iterator first, Iterator last) { ... }

Then I call this function on blaVec with:

doSomething(blaVec.begin(), blaVec.end());

However, I really would like something shorter like doSomething(blaVec)开发者_运维百科 but without having to specify vector in function definition. Basically, is there a good standard way to specify just the first iterator or maybe a range of [begin,end] iterators as is done by Boost.Range.

I'm an algorithms guy so I really don't want to get into overly generic complex solutions. Most of my life I wrote functions like this:

void doSomething(vector<int> & bla) { ... }

However, these days, I frequently write doSomething that operates on list and deque and vector so a slightly more generic solution was called for, which is why I went with iterators. But it just seems to be too verbose of a solution. What do you suggest?

  1. doSomething(vector & bla) { ... }
  2. doSomething(Iterator first, Iterator last) { ... }
  3. doSomething(/* some range data structure */) { ... }


If you find that verbose, then you can wrap that with this:

template<typename Container>
void doSomething(Container &c) 
{
  doSomething(c.begin(), c.end()); //internally call the iterator version.
}

And use this function, instead of iterator version.

Also, you can use iterator version, when you don't want the function to operate on all elements in the container. For example,

doSomething(c.begin(), c.begin() + 5); //operate on first 5 elements
                                       //assuming c.begin()+5 makes sense


Prefer the second one, as it is lot more flexible.

I don't feel it is verbose, but if you really insist, you might want to define a macro for it, eg:

#define FULLITER(a) a.begin(), a.end()

(just make sure a is a simple expression so it's not executed twice.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜