使用迭代器 C++ 打印向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33218031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Print a vector using iterator c++
提问by elena.bdc
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)
我想我正在转换我收到的 int 类型的字符串。也许我没有以正确的方式使用迭代器(我认为这是问题所在,但我真的不知道)
Thanks in advance.
提前致谢。
回答by L?rne
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. I didn't understand what you tried to do with the loop over j
, so I discarded it.
请注意,我*
用来将迭代器更改it
为它当前正在迭代的值。我不明白你试图用循环来做什么j
,所以我放弃了它。
回答by NathanOliver
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
您没有取消引用it
并且没有输出 a 的函数,vector<int>::iterator
因此您收到编译器错误。将您的代码更改为
cout << "\t" << *it;
Should fix it.
应该修复它。
As a side what is the nested for loop for?
另一方面,嵌套的 for 循环是什么?