Victor Amaro Victor Amaro - 1 year ago 88
C++ Question

What to use when I am not sure of the type? Issue in printing vector elements

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

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 >}'


'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) {

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

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;
return 0;

Answer Source

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 << ' ';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download