簡體   English   中英

使用迭代器 C++ 打印向量

[英]Print a vector using iterator c++

我想使用迭代器打印一個向量:

#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;
    }
}

我收到此錯誤:

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;

你可以幫幫我嗎?

我想我正在轉換我收到的 int 類型的字符串。 也許我沒有以正確的方式使用迭代器(我認為這是問題所在,但我真的不知道)

提前致謝。

如果你想在向量中打印int s,我猜你想使用:

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

請注意我用*改變迭代it轉化成其當前迭代的價值。 我不明白你試圖用j上的循環做什么,所以我放棄了它。

在您更新的代碼中,您有

cout <<  "\t" << it;

您沒有取消引用it並且沒有輸出vector<int>::iterator因此您會收到編譯器錯誤。 將您的代碼更改為

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

應該修復它。

另一方面,嵌套的 for 循環是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM