STL Vector push_back()

STL Vector push_back()

本文关键字:back Vector push STL      更新时间:2023-10-16

我发现了以下示例。我以前没有使用过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'']

ypush_backed,不用作索引,因此不是

[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::mapstd::map

std::map<int,std::map<int,UNKNOWN_DATATYPE> A;