Jam*_*lis 11
执行此操作的最佳方法是使函数采用一对迭代器:一个到范围的开头,一个到范围的结尾(实际上是"一个结束"的范围):
template <typename ForwardIterator>
void f(ForwardIterator first, ForwardIterator last)
{
for (ForwardIterator it(first); it != last; ++it)
std::cout << *it;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用任何范围调用这个函数,无论该范围来自数组,字符串还是任何其他类型的序列:
// You can use raw, C-style arrays:
int x[3] = { 1, 2, 3 };
f(x, x + 3);
// Or, you can use any of the sequence containers:
std::array<int, 3> v = { 1, 2, 3 };
f(v.begin(). v.end());
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请考虑为自己准备一本好的C++入门书.