矢量不从CIN服用输入

问题描述 投票:0回答:1

我试图从cin输入元素cin>>ngarmy[]i但所有元素保持为零在整个程序谁能告诉我什么是错的载体?

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector <int> ngarmy(100);
vector <int> nmarmy(100);
int main() {
    int t;
    cin >> t;
    while (t--) {
        int ng, nm;
        cin >> ng >> nm;
        for (int i = 0; i < ng; i++) {
            cin >> ngarmy[i];
        }
        for (int i = 0; i < nm; i++) {
            cin >> nmarmy[i];
        }
        sort(ngarmy.begin(), ngarmy.end());
        sort(nmarmy.begin(), nmarmy.end());
        int i = 0, j = 0;
        int ans = 0;
        while (1) {
            if (ngarmy[i] < nmarmy[j]) {
                i++;
                if (i == ng) {
                    ans = 1;
                    break;
                }
            }
            else {
                j++;
                if (j == nm) {
                    ans = 2;
                    break;
                }
            }

        }
        if (ans == 1)
            cout << "MechaGodzilla" << endl;
        else
            cout << "Godzilla" << endl;
    }
}
c++ vector
1个回答
4
投票

该矢量大小100,但大多是零,因为你没有100级的输入。当您在向量排序的所有零前来向量的开始,因为零是最小的号码。

您错误地阅读载体。相反,具有矢量总是大小100你应该让他们同样大小的你输入的数量。在零号开始的载体和使用push_back当你读了一些,以增加向量的大小。

像这样

vector <int> ngarmy; // vectors are size zero
vector <int> nmarmy;

    for (int i = 0; i < ng; i++) {
        int n;
        cin >> n;
        ngarmy.push_back(n); // add n to the vector
    }
    for (int i = 0; i < nm; i++) {
        int n;
        cin >> n;
        nmarmy.push_back(n); // add n to the vector
    }

或者,正如在评论中建议,你可以只resize载体,以合适的尺寸

vector <int> ngarmy;
vector <int> nmarmy;

    ngarmy.resize(ng);
    for (int i = 0; i < ng; i++) {
        cin >> ngarmy[i];
    }
    nmarmy.resize(nm);
    for (int i = 0; i < nm; i++) {
        cin >> nmarmy[i];
    }
© www.soinside.com 2019 - 2024. All rights reserved.