2017-01-07 103 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;