C++ 通用 int 数组和 vector 迭代器

标签 c++ arrays oop templates iterator

在下面的代码中,我需要定义一个迭代器,它可以迭代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/

相关文章:

C++ vector 错误(Visual C++ 2008 Express Edition)

c++ - Cocos2d-x 我如何分派(dispatch) N 个节点 Action 动画,它们之间有延迟

c - qsort 段错误结构

PHP 尝试在 WooCommerce Api 2.0.1 中获取订单 ID 创建订单功能

ios - 将 UIPickerView 放置在 UIAlertController 的中心

c++ - 实现类似 std::vector.back() 的东西

python - 使用字典在循环中创建不同的实例

c++ - 将子序列问题的复杂性从指数降低到多项式?

c++ - 关于vc中的系统

c# - 具有返回修改后的父级的方法的设计模式