这个程序崩溃了,为什么?

问题描述:

#include<iostream> 
#include<vector> 
#include<algorithm> 
using namespace std; 
int main() 
{ 
    vector<pair<int,int> > arr; 
    arr[0].first=20,arr[0].second=1; 
    arr[1].first=3,arr[1].second=2; 
    arr[2].first=230,arr[2].second=3; 
    arr[3].first=230,arr[3].second=4; 
    arr[4].first=202,arr[4].second=5; 
    arr[5].first=-20,arr[5].second=6; 
    sort(arr.begin(),arr.end()); 
    vector<pair<int,int> >::iterator it; 
    for(it=arr.begin();it!=arr.end();it++) 
    { 
     cout<<it->first<<it->second<<endl; 
    } 
} 

此程序运行不正常,背后有什么可能的原因?
此外,我想有排序对矢量的排序完成的价值。这个程序崩溃了,为什么?

+0

[ 'vector > arr(6);'](http://en.cppreference.com/w/cpp/container/vector/vector)应该解决这个问题。 –

+2

请问每个问题有一个问题。 –

+2

使用默认构造函数创建矢量时,矢量为***空***。任何索引都会超出范围并导致*未定义的行为*。 –

分配给vector不分配内存。
通常我们使用push_back来添加具有自动记忆
分配的项目。这样的代码,你平时写像这样:

arr.push_back(pair<int, int>(20, 1)); 
arr.push_back(pair<int, int>(3, 2)); 

等。

但现在与C++ 11这种编码方式是旧的。
这是可能做到这一点像(见环路):

arr.push_back({ 20, 1 }); 
arr.push_back({ 3, 2 }); 
sort(arr.begin(), arr.end()); 
for (auto p : arr) 
{ 
    cout << p.first << p.second << endl; 
} 

事实上,C++ 11把一些方便的语法到构造函数:

vector<pair<int, int> > arr{ { 20, 1 }, { 3, 2 }, { 230, 3 }, 
{ 230, 4 }, { 202, 5 }, { -20, 6 } }; 
sort(arr.begin(), arr.end()); 
for (auto p : arr) 
{ 
    cout << p.first << ", " << p.second << endl; 
} 
+1

“vector >” - 同样在C++ 11中,关闭尖括号之间的空间不再是必需的。但是,'template struct d; d 2)> x;'...... –

不像map::operator[]vector::operator[]从来汽车 - 在容器中插入一个新元素。访问不存在的元素是未定义的行为(在调试模式下,运行时可能会抛出断言来帮助调试)。

在C++ 11种的最有效的方式来填充载体是:

通过初始化列表:

vector<pair<int, int>> arr { 
    { 20, 1 }, { 3, 2 }, { 230, 3 }, 
    { 230, 4 }, { 202, 5 }, { -20, 6 } }; 

或者创建就地条目:

vector<pair<int, int>> arr; 
    arr.reserve(6); // optional, is just for efficiency 
    arr.emplace_back(20, 1); 
    arr.emplace_back( 3, 2); 
    arr.emplace_back(230, 3); 
    arr.emplace_back(230, 4); 
    arr.emplace_back(202, 5); 
    arr.emplace_back(-20, 6); 
+0

为什么不通过ctor也是“最高效”的方式分配内存? – 5208760

+0

你的意思是'arr(6);'?这不仅仅分配内存,它还默认构造6个元素。当然,'default '默认构造函数是无操作的,但这种方法仍然更容易出错(如果不是每个元素都随后被设置,则使用未初始化值的风险)。如果默认构造函数确实发生初始化元素,那么这将是浪费。 – rustyx