簡體   English   中英

向量數組輸入問題,可能是索引問題

[英]Array of Vectors input problem, possibly an indexing one

我無法理解為什么我的向量數組沒有輸入一行。 ...

#include<bits/stdc++.h>
using namespace std;
int main () {
    int r;
    cin>>r;
    vector <int> v[r];
    for (int i=0; i<r; i++) {
        for (int j=0; j<i; j++) {
        int x;
        cin>>x;
        v[i].push_back(x);
        }
    }
    for (int i=0; i<r; i++) {
        for (size_t j=0; j<v[i].size(); j++){
            cout<<v[i][j];
        }    
        cout<<endl;
    }

}

...有輸入...

5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5

...它輸出...

7
38
810
2744

...在 output 的開頭有一個空行。

您在 output 的開頭看到了空行,因為v[0]是空的。 您可以通過以下方式修復它:

#include<bits/stdc++.h>
using namespace std;
int main () {
    int r;
    cin>>r;
    // vector <int> v[r];
    //                ^
    // This is variable length array which is not really legal in C++. Use:
    vector<vector<int>> v;
    v.resize(r);
    for (int i=0; i<r; i++) {
        for (int j=0; j<=i; j++) {
        //             ^^
        // This loop had 0 iterations when i == 0, 1 when i == 1, ..., 4 when i == 4.
        // So you need to do one more iteration each time.
            int x;
            cin>>x;
            v[i].push_back(x);
        }
    }
    for (int i=0; i<r; i++) {
        for (size_t j=0; j<v[i].size(); j++){
            cout<<v[i][j];
        }    
        cout<<endl;
    }

}

還:

#include <iostream>
#include <vector>

問題就在一行中(在下面的代碼正文中注釋)。 此外,我將您的代碼更改為更類似於 c++。

//#include<bits/stdc++.h> //Include all libraries is a bad practice. Include just what you need
#include <vector>
#include <iostream>

using namespace std;

int main () {
    int r;
    cin >> r;

    vector<vector<int>> v(r, vector<int>());    //more secure than c-style vector<int> v[r]
                                                //and create the 1st level of vector
    for (int i = 0; i < r; ++i)
         for (int j = 0; j < i; ++j) {          //Here is the issue
             v[i].emplace_back();
             cin >> v[i].back();
         }

    for (auto& i : v) {                         //Iterate over the 1st level of vector
        for (auto& j : i)                       //Iterate over the 2nd level of vector
            cout << j << ' ';
        cout << '\n';
    }

    return 0;
}

暫無
暫無

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

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