[英]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.我想我正在转换我收到的 int 类型的字符串。 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 :如果你想在向量中打印
int
s,我猜你想使用:
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.请注意我用
*
改变迭代it
转化成其当前迭代的价值。 I didn't understand what you tried to do with the loop over j
, so I discarded it.我不明白你试图用
j
上的循环做什么,所以我放弃了它。
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.您没有取消引用
it
并且没有输出vector<int>::iterator
因此您会收到编译器错误。 Changing you code to将您的代码更改为
cout << "\t" << *it;
Should fix it.应该修复它。
As a side what is the nested for loop for?另一方面,嵌套的 for 循环是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.