简体   繁体   中英

Print a vector using iterator c++

I want to print a vector using an iterator:

#include <vector>
#include <istream>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <math.h>
using namespace std;

typedef vector<int> board;
typedef vector<int> moves;


int sizeb;
board start;
moves nmoves;
istringstream stin;


board readIn(std :: istream& in ) {
    int val;
    while (in >> val)
    start.push_back(val);

    sizeb = start[0];
    return start;
}


void printboard(board n) {
    int sizem = sizeb*sizeb;
    int i = 1;

    for (vector<int>::iterator it = start.begin() ; it != start.end(); ++it) {
        for (int j = 0; j < sizeb; ++j)
            cout <<  "\t" << it;
        cout << endl;
    }
}

And I receive this error:

error: invalid operands to binary expression
  ('basic_ostream<char, std::__1::char_traits<char> >' and
  'vector<int>::iterator' (aka '__wrap_iter<pointer>'))
                    cout <<  "\t" << it;

Could you help me?

I think I'm converting a string that I receive in a int type. Maybe I'm not using on the right way the iterator (I think that's the problem, but I don't really know)

Thanks in advance.

If you want to print the int s in the vector, I guess you want to use :

for (vector<int>::iterator it = start.begin() ; it != start.end(); ++it)
    cout << "\t" << *it;

Notice I use * to change the iterator it into the value it's currently iterating over. I didn't understand what you tried to do with the loop over j , so I discarded it.

In your updated code you have

cout <<  "\t" << it;

You are not dereferecing it and there is no function to output a vector<int>::iterator so you are getting a compiler error. Changing you code to

cout <<  "\t" << *it;

Should fix it.

As a side what is the nested for loop for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM