Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

my c++ code does not let me input all input values, and i don't know why

using namespace std;

int main() {
    int t;
    cin >> t;
    for (int j = 0; j < t; j++) {
        int n;
        cin >> n;
        vector<string> cities;

        for (int i = 0; i < n; i++) {
            cin >> cities[i];
        }
        int size = cities.size();
        for (int i = 0; i < n; i++) {
            for (int k = 1; k < n; k++) {
                if (cities[i] == cities[k]) size--;
            }
        } 
        cout << size << '
';
    }
    
}

So, this task is from kattis website(link: https://open.kattis.com/problems/everywhere) and the goal is to get the number of the cities someone has visited, the problem is that some of these cities were visited twice or even more, so the only thing we need is to get the number of cities.

That's how input looks like:

7
saskatoon
toronto
winnipeg
toronto
vancouver
saskatoon
toronto
3
edmonton
edmonton
edmonton

And my code doesn't let me input the whole input, I mean, I input 3 values and then program stops working. Can you help me?

question from:https://stackoverflow.com/questions/65645753/my-c-code-does-not-let-me-input-all-input-values-and-i-dont-know-why

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You forgot to initialize your vector with a size. You can do it by passing n to the constructor:

vector<string> cities(n);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...