这个程序崩溃了,为什么?
问题描述:
#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;
}
}
此程序运行不正常,背后有什么可能的原因?
此外,我想有排序对矢量的排序完成的价值。这个程序崩溃了,为什么?
答
分配给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
答
不像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);
[ 'vector> arr(6);'](http://en.cppreference.com/w/cpp/container/vector/vector)应该解决这个问题。 –
请问每个问题有一个问题。 –
使用默认构造函数创建矢量时,矢量为***空***。任何索引都会超出范围并导致*未定义的行为*。 –