Garmaine Staff asked 2 years ago

I'm trying to use displayVectorVer2() to have it only display the first 10 elements, but I don't know how to do it with iterators. I did try a few dumb things just to see what would happen: I compared the iterator to displayLimit in my for loop. I played around by subtracting vobj.end()-5 since my professor is only having me use 15 elements, but I fully well knew this was not a good idea.

#include <iostream>
#include <vector>
#include <ctime>

template <class T>
void fillVector(std::vector<T>& vobj, int n);

template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr);

template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
    srand((unsigned int)time(NULL));
    for (int i=0; i<n; ++i)
    {
        vobj.push_back(rand()%99999+1);
    }
}

template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr)
{
    std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;

    const unsigned displayLimit = 10;
    if (vobj.size()>displayLimit)
    {
        for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
        {
            std::cout << "  " << *ptr;
        }
        std::cout << "  ..." << std::endl;
    }
    else
    {
        for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
        {
            std::cout << "  " << *ptr;
        }
        std::cout << std::endl;
    }
}

int main()
{
    std::vector<int> vobj;
    std::cout << "Before calling fillVector(...): vobj contains " 
              << vobj.size() << " values." << std::endl;

    std::cout << "\nEnter # of random values you'd like to store in vobj: ";
    int n;
    std::cin >> n;

    std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
    fillVector(vobj, n);

    std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
    std::vector<int>::iterator ptr;
    displayVectorVer2(vobj,ptr);
}