Victor Amaro Victor Amaro - 3 months ago 9
C++ Question

How to print a vector using an iterator?

I was having an issue trying to print out the contents of a vector in my

printVec
function. What would be the correct way to print out the contents of it? I'm getting an error of, no match for 'operator=' (operand types are 'std::vector::iterator {aka __gnu_cxx::__normal_iterator >}' and 'std::vector::const_iterator {aka __gnu_cxx::__normal_iterator >}')

#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>
using std::cout; using std::setw; using std::vector; using std::sort;

const int VEC_SIZE = 250;
const int VEC_LOW = 1;
const int VEC_HIGH = 10000;

void genRandNums(vector <int>& vecList) {
srand(1);

for(int i = 0; i < VEC_SIZE; i++) {
int randNum = rand() % (VEC_HIGH - VEC_LOW + 1) + VEC_LOW;
vecList.push_back(randNum);
}

sort(vecList.begin(), vecList.end());
}

void printVec(const vector <int>& vecList) {
vector<int>::iterator vecIt;

for(vecIt = vecList.begin(); vecIt < vecList.end(); vecIt++)
cout << *vecIt << setw(5);
}

int main() {
vector<int> vectorList;
genRandNums(vectorList);
printVec(vectorList);
return 0;
}

Answer

Use the keyword auto when you are not sure of the type. And to know what exactly the type is, hoover your mouse on the variable on run time.

This should work:

void printVec(const vector <int>& vecList) 
{
    //const vector<int>::iterator vecIt;

    for (auto vecIt = vecList.begin(); vecIt != vecList.end(); vecIt++) // add "auto" as the declaration type 
        cout << *vecIt << setw(5);
}

Another approach as NathanOliver mentioned is to use the Range-Based for loop like this:

for (const int& i : vecList) // access by const reference
        cout << i << ' ';
Comments