vector 为什么不可以直接用cin插入的故事

vector
http://www.cplusplus.com/reference/vector/vector/?kw=vector
template < class T, class Alloc = allocator<T> > class vector; // generic template

当你写个程序比如下面这个
#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;
}

 你会发现欸, 程序怎么突然挂了  异常退出

 那是因为上面的程序 vector 只是声明而已, 并没有开辟内存  你有如下两种选择

 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; }


猜你喜欢

转载自www.cnblogs.com/163467wyj/p/12008751.html
今日推荐