2017-01-07 107 views
-1

我找到了下面的例子。我没有使用STL之前,我想知道它在干什么STL向量push_back()

#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);。根据我在documentation中看到的,它在矢量的末尾添加了一个新元素,并将矢量大小增加了1。由于我正在阅读一对数字(x,y),这是否意味着在每读完x后,将会有一个?所以最后我的向量就像[x] [y] [x'] [y'] [x''] [y'']?

+0

题外话,这种做法是在使用点之前声明的变量,而不是* *正好一个范围。 – LogicStuff

+3

'vector A [maxn];'是一个数组(向量)。 – LogicStuff

+0

如果'x> = 100010'会怎么样?在该循环中是一个超出界限的访问。 – PaulMcKenzie

回答

0

因为我读的是一对数字(x,y),这是否意味着在每读x之后都会有y?

不,它不。用户可能输入一个非整数,如“fubar”,并导致scanf失败。没有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_back ED,而不是作为一个指标,所以而非

[x][y][x'][y'][x''][y''] 

A看起来更像

[x][0] == y 
[x'][0] == y' 
[x''][0] == y'' 

与任何A[i],其中没有x,y对被提供为空的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 S:

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