读取数字进行向量 [英] Read numbers to vector

查看:87
本文介绍了读取数字进行向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为此苦苦挣扎.基本上,我必须先阅读一个数字:

I'm struggling hard with this. Basically, I have to read a number first:

int n;
scanf("%d", &n);

然后我必须读取N个间隔到向量:

Then I have to read N intervals to a vector:

vector< vector<int> > intervals;
int a, b;
for (int i = 0; i < n; i++) {
  scanf("%d %d", &a, &b);
  intervals.at(i).at(0) = a;
  intervals.at(i).at(1) = b;
}

使用GDB调试器,我得到了:

Using GDB debugger, I get this:

3
1 4
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check

Program received signal SIGABRT, Aborted.
0x00007ffff7260c35 in raise () from /lib/libc.so.6
(gdb) 

任何关于我做错事情的想法吗?谢谢!

Any idea of what I'm doing wrong? Thank you!

推荐答案

intervals.at(i).at(0) = a;

是非法的,因为您的向量最初是空的.您可以使用push_back或预先分配向量.

Is illegal, since your vector is initially empty. You can either use push_back or pre-allocate the vector.

我会预先分配向量,因为这不需要在push_back上进行进一步的重新分配:

I would pre-allocate the vector, since this would require no further re-allocation on push_back:

vector< vector<int> > intervals(n);
int a, b;
for (int i = 0; i < n; i++) {
  scanf("%d %d", &a, &b);
  intervals.at(i).push_back(a);
  intervals.at(i).push_back(b);
}

这篇关于读取数字进行向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆