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

时间:2016-08-28 12:34:04

标签: c++ sorting vector stl

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

这个程序运行不正常,背后可能的原因是什么?
此外,我想要排序对向量,其中排序由值完成。

2 个答案:

答案 0 :(得分:3)

分配给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 :(得分:0)

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);
相关问题