Suppose I want to implement a class that iterates over some range, and stores those values in an array at random indices. So I want something where I can write:
string s = "Steve";
auto r1 = RandomArray<string>(s.begin(), s.end());
// Or even better:
auto better1 = RandomArray(s);
int a[] = {1,2,3};
auto r2 = RandomArray<int>(begin(a), end(a));
// Or even better:
auto better2 = RandomArray(a);
// Later on...
for (const auto ch: r1) {/* do something */}
How would I define such a class? I can't figure out what the templating should look like. That is, how do I fill in what's missing below?
// template stuff
class RandomArray {
public:
RandomArray(/* some iterator argument(s) */) {
// Pretend arr_ has already been sized correctly.
for (const auto it = /* iterate over iterator */) {
arr_[randomIndex()] = it;
}
}
private:
/* Some type */ arr_[];
};
I'm ignoring all the other things I'd eventually need (move constructors, begin/end, etc.). I just want to figure out what the template statement before the class should look like.
Aucun commentaire:
Enregistrer un commentaire