Why not use cin vector inserted directly Story

Vector 
http://www.cplusplus.com/reference/vector/vector/?kw=vector
Template <class T, the allocator class of Alloc = <T>> class Vector; // Generic Template

when you write a procedure such as the following
#include <bits/stdc++.h>

int main(){
    int n; 
    std::cin >> n;
    std::vector<int> v;
    for(int i = 0; i < n; i++)    std::cin >> v[i];

    for(int i = 0; i < n; i++)    std::cout << v[i] << " ";
    return 0;
}

 You will find Hey, how suddenly hung up a leave program

 That is because the above program vector just declare it, and did not open up the memory you have the following two options

 1) If you know the size of vector will be (in your case/example it's seems you know it):

#include <bits/stdc++.h>

int main(){
    int n; 
    std::cin >> n;
    std::vector<int> v(n);
    for(int i = 0; i < n; i++)    std::cin >> v[i];

    for(int i = 0; i < n; i++)    std::cout << v[i] << " ";
    return 0;
}
2) if you don't and you can't get it in you'r program flow then:
#include <bits/stdc++.h>

int main(){
    int n; 
    std::cin >> n;
    std::vector<int> v;
    for(int i = 0; i < n; i++)   {
        int x;
        std::cin >> x; 
        v.push_back(x);  
    } 
for(int i = 0; i < n; i++) std::cout << v[i] << " "; return 0; }

 



Guess you like

Origin www.cnblogs.com/163467wyj/p/12008751.html