C++ STL矢量推回()

C++ STL矢量推回(),c++,vector,stl,C++,Vector,Stl,我发现了下面的例子。我以前从未使用过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, &Star

我发现了下面的例子。我以前从未使用过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;
}
#包括
#包括
使用名称空间std;
#定义maxn 100010
int N,M,L,开始;
向量A[maxn];
int main()
{
int i,x,y;
scanf(“%d%d%d”、&N、&M和&Start);
对于(i=1;i
因为我在读一对数字(x,y),这是否意味着每次读x之后都会有一个y

不,不会。用户可能输入非整数,如“fubar”,并导致scanf失败。没有针对scanf失败的测试,因此程序可能会接受x而不接受y

scanf
返回成功读取的输入数,因此

if (scanf("%d %d ", &x, &y) == 2)
{
    A[x].push_back(y);
}
else
{
    // Inform user of error
}
将捕获简单错误

最后我的向量是[x][y][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''

使用任何<代码> A[i] <代码>,其中没有x,y对被提供为空<代码>向量< /代码>。要保持示例简单,请考虑输入3×3, 3 3, 5×7 /p>

[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
of
std::map
s:

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

std::mapOff主题,实践是在使用点声明变量,而不是之前的一个范围。
vector A[maxn];
是一个(向量的)数组。如果
x>=100010
?在该循环中是越界访问。@Danh:如果你认为阅读一本好书会有帮助,那么留下一条链接到该列表的注释是可以的,但这不是一个好的重复目标。