STL Vector push_back()
STL Vector push_back()
我发现了以下示例。我以前没有使用过STL,我想了解它在做什么
#include <stdio.h>
#include <vector>
using namespace std;
#define maxn 100010
int N, M, L, Start;
vector <int> A[maxn];
int main()
{
int i, x, y;
scanf("%d %d %d ", &N, &M, &Start);
for (i = 1; i <= M; i++)
{
scanf("%d %d ", &x, &y);
A[x].push_back(y);
}
return 0;
}
我说的是A[x].push_back(y)。从我在文档中看到的情况来看,它在向量的末尾添加了一个新元素,并将向量的大小增加了一。由于我正在读取一对数字(x,y),这是否意味着每次x读取后都会有一个y?所以最终我的向量会是类似于[x][y][x'][y'][x''][y']的?
由于我正在读取一对数字(x,y),这是否意味着每次读取x后都会有一个y?
没有。用户可以输入一个非整数,例如"fubar",从而导致scanf失败。没有扫描失败的测试,因此程序可能会接受没有y的x。
scanf
返回成功读取的输入数,因此
if (scanf("%d %d ", &x, &y) == 2)
{
A[x].push_back(y);
}
else
{
// Inform user of error
}
将捕获简单的错误。
所以最终我的向量会是类似于[x][y][x'][y'][x''][y'']
y
是push_back
ed,不用作索引,因此不是
[x][y][x'][y'][x''][y'']
A
看起来更像
[x][0] == y
[x'][0] == y'
[x''][0] == y''
其中没有提供x、y对的任何A[i]
是空的vector
。为了使示例保持简单,请考虑输入3 3、3 3、5 7
[0][0] == out of range access. undefined behaviour
[1][0] == out of range access. undefined behaviour
[2][0] == out of range access. undefined behaviour
[3][0] == 3
[3][1] == 3
[3][2] == out of range access. undefined behaviour
[4][0] == out of range access. undefined behaviour
[5][0] == 7
[5][1] == out of range access. undefined behaviour
[6][0] == out of range access. undefined behaviour
[7][0] == out of range access. undefined behaviour
...
[10010][0] == out of range access. undefined behaviour
获取
[x][y][x'][y'][x''][y'']
我怀疑您需要实现一个稀疏数组数据结构,但我不确定。穷人的解决方案是使用std::map
的std::map
:
std::map<int,std::map<int,UNKNOWN_DATATYPE> A;
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 推导 std::vector::back() 的返回类型
- vector.back() 和 vector[vector.size() - 1] 之间的区别?
- vector.push_back(vector.back()+1) 是未定义的行为吗?
- std::vector using back(), pop_back(), push_back(), 得到'double free or corruption'错误
- vector.back()和vector.end()有什么区别
- vector.back() 可以用来为向量的最后一个元素赋值吗?
- 在std::vector中实现back()
- std::vector back()的奇怪行为
- 修改向量后引用 vector.back() 的奇怪行为
- std::vector::back 和 vector::operator[ vector::size() - 1] 之间
- 为什么对std::vector::back()的调用会使我的程序崩溃