在下面的代码中,我需要定义一个迭代器,它可以迭代vector<int>
。和 int[100]
.如何定义mi
这里?
template<class arraytype>
void array_show(arraytype array, size_t arraySize)
{
// how to define mi????
for (mi = array; array != m.end(); array++)
std::cout << " " << *mi << std::endl;
}
最佳答案
尝试以下操作
#include <iostream>
#include <vector>
#include <iterator>
template<class arraytype>
void array_show( const arraytype &array )
{
for ( const auto &x : array ) std::cout << x << ' ';
std::cout << std::endl;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> v( std::begin( a ), std::end( a ) );
array_show( a );
std::endl( std::cout );
array_show( v );
std::endl( std::cout );
return 0;
}
程序输出为
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
另一种方法是使用迭代器。例如(这里显示了两个函数定义)
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template<class arraytype>
void array_show( const arraytype &array )
{
for ( const auto &x : array ) std::cout << x << ' ';
std::cout << std::endl;
}
template <class InputIterator>
void array_show( InputIterator first, InputIterator last )
{
typedef typename std::iterator_traits<InputIterator>::value_type value_type;
std::copy( first, last,
std::ostream_iterator<value_type>( std::cout, " ") );
std::cout << std::endl;
}
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
std::vector<int> v( std::begin( a ), std::end( a ) );
array_show( std::begin( a ), std::end( a ) );
std::endl( std::cout );
array_show( std::begin( v ), std::end( v ) );
std::endl( std::cout );
return 0;
}
程序输出同上
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
您可以自己编写一个循环来代替算法 std::copy。例如
template <class InputIterator>
void array_show( InputIterator first, InputIterator last )
{
for ( ; first != last; ++first )
{
std::cout << *first << ' ';
}
std::cout << std::endl;
}
关于C++ 通用 int 数组和 vector 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29816898/