簡體   English   中英

在For循環中遍歷C ++向量

[英]Iterating through C++ Vectors in a For loop

我的代碼出了點問題。 它正在編譯,但是結果不是我期望的,盡管我可以確定我的問題之一,但是我想知道我是否走錯了路。

我創建了一個名為test的類:

`
class test{

private:

//have moved the variables to public 
//so it's easy to see what's in the vector. 

public:

    int my_id, my_x,my_y,width, height;

test (int button_id=0, int x=0, int y=0, int width=0, int height=0)
{
    my_x = x;
    my_y = y;

    width = width;
    height = height;

}

~test()
{}

void handle_event()
{}

};

`

現在我想用這些對象填充向量,並從文本文件中初始化它們的值。

這是我的方法:

int main(int argc, char const *argv[])
{

    //setup file
    ifstream inputFile("data.dat");
        const char* filename = "data.dat";
              std::ifstream inFile(filename);



    //init Vector
    vector<test> buttons;
        int id, x, y, width,height;
        int max_buttons = count(istreambuf_iterator<char>(inputFile),istreambuf_iterator<char>(), '\n');


    // Make sure the file stream is good
    if(!inFile) {
                cout << endl << "Failed to open file " << filename;
                return 1;
                }


  //Iterate fields into Vector,

  for (id=0 ; id < max_buttons ; id ++) 

  {

    inFile >> x >> y >> width >> height;

    buttons.push_back(test(id,x,y,width,height));    
    cout << std::setw(10) << x << y << width <<height <<endl;

  }

  cout << endl;

for(int p=0; p < 10; p++) // 

  cout << buttons[p].my_id << endl;

    return 0;
}

我已經將類中的變量移到了公共位置,所以看一下它們會更容易,一旦發現問題,我就會將它們移回去。 某些字段正確填充(x和y變量),但id並非每次調用都增加。 我有一個完整的向量,但有廢話數據。 我意識到直接從文本文件中解析數據意味着它將采用char格式,並且與整數類型不兼容,但是為什么我的ID沒有增加?

提前致謝!

這是數據:

23 16 10 19
24 40 10 17
23 16 10 16
25 40 10 14
26 16 10 10
27 40 10 12
27 36 10 11
28 40 10 13
29 34 10 18
27 49 10 10

您沒有在測試類的構造函數中分配my_id。

將此行添加到您的構造函數中:

my_id = button_id;

您沒有在構造函數中更改對象的ID。 因此將其更改為以下內容

test (int button_id=0, int x=0, int y=0, int width=0, int height=0)
{
    my_id = button_id;
    my_x = x;
    my_y = y;

    width = width;
    height = height;

}

嘗試編譯警告標志(例如-Werror-Wall-pedantic等),以便將您的代碼標記為構造函數中未使用的變量之類的東西,並且您甚至在錯誤發生之前就已經知道了它的錯誤!

另外,您不應該通過計算換行數來計算文件中的對象數,這有兩個原因

  1. 如果某些地方沒有換行怎么辦? 例如在某些物體之后。
  2. 它需要循環兩次文件

您應該像下面這樣循環:

while(inFile >> x >> y >> width >> height) { ... }

當文件中缺少4個變量中的任何一個時,這將返回false,因為istream將進入“ false”狀態並且循環將自行停止

暫無
暫無

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

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