简体   繁体   中英

Best Practice: Passing Arrays of Data

Lately I've had several cases where I've needed a user to pass a set of data to a method. It seems very un-generic to have a parameter be a const std::vector<stuff>& (or any particular container or array).

Is there a way I can (and should) pass groups of data to a method generically?

Pass two iterators, or, with c++11 you can use ranges. This is how C++ algorithms typically do it.

EDIT: I misremembered the new range-based for loops http://en.cppreference.com/w/cpp/language/range-for as having generic ranges for algorithms. Just pass two iterators to indicate a range for general purpose algorithms.

Of course. You can pass iterators.

I guess Mark B means the range-based for loop (http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html). You need to provide begin() and end() in you array class with iterator that implements increment operator ++, inequality operator != and a dereference operator *

However I'm in favor of passing two iterators, because it works with ordinary arrays too. You just pass pointers to the first element of an array and the last element of an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM