二维矢量分割错误

时间:2017-12-09 07:05:20

标签: c++ stdvector

以下代码给我一个分段错误,我不明白这个问题。我认为我使用矢量的方式有些错误,但我不知道那是什么。请帮忙。

#include<iostream>  
#include<sstream>  
#include<vector>  
#include<algorithm>

using namespace std;  

int main()  
{
    int T;
    vector<int>n,m;
    vector<vector<int> >arr;
    int temp;
    cin>>T;
    for(int i=0;i<T;i++) 
    {
        cin>>temp;
        n.push_back(temp);
        cin>>temp;
        m.push_back(temp);
        vector<int>temp_vec(temp);
        for(int j=0;j<temp;j++)
        {
            int temp2;
            cin>>temp2;
            temp_vec[j]=(temp2);
        }
        sort(temp_vec.begin(),temp_vec.end());
        arr.push_back(temp_vec);
        cout<<endl;
    }
    return(0);
}

1 个答案:

答案 0 :(得分:-2)

当您声明任何类型的向量时,在初始化并将值放入其中之前,它没有任何元素。你的代码:

arr.push_back(temp_vec);

正尝试将temp_vec插入位于 0 位置的向量arr内的不存在的向量中。

您应该知道要使用的向量的大小,然后使用构造函数的大小初始化它:

vector<vector<int> >arr(size);

例如:

vector<vector<int> >arr(64);

这将使用64或x个空元素初始化向量arr

this

相同