2017-04-14 56 views
0

我想通過循環使用for循環來檢查不同向量的大小。使用for循環遍歷多個向量

#include <vector> 
#include <iostream> 

using namespace std; 

vector<int> V1; 
vector<int> V2; 
vector<int> V3; 

for (int i=0;i<3;i++){ 
    cout<<Vi.size()<<endl; 
} 

不幸的是,我不知道是否有可能通過向量名重複,如果是,如何寫參數我這樣,我的編譯器知道,這是我的循環的整數。

在此先感謝。

+2

考慮製作一個數組或矢量向量(嵌套數組)。否則宏必須涉及 –

+7

'for(auto * v:{&V1,&V2,&V3}){cout << v-> size()<< endl; }'? [演示](https://ideone.com/6wf6Wo)。 –

回答

0

有沒有辦法做你嘗試什麼特定的方式做,又名評估i到其在Vi.size()變量名值,因爲編譯器計算這一個名爲Vi變量不存在。然而,正如其他人所指出的那樣,你可以做到這一點不同,但仍然得到同樣的結果,這裏有幾個例子:

感謝@ kerrek-SB爲這一個(可能是最好的選擇):

for (auto* v : {&V1, &V2, &V3}) { std::cout << v->size() << std::endl; } 
(:;:如圖所示簡單的爲您的目的下行上攻添加你必須使用動態分配和複製的更多的載體):

const int size = 3; // Or whatever size you want 
// needs to be const because c++11 and up don't support variable length arrays(VLAs) 
std::vector<int> V[size]; 
V[0].push_back(0); // Appends integer to vector 
V[0].push_back(10); 
V[1].push_back(1); 
V[2].push_back(2); 
for (int i = 0; i < size; i++) { 
    std::cout << V[i].size() << std::endl; 
} // OUTPUT: 
    // 2 
    // 1 
    // 1 

使用指針數組已創建載體(下行:

使用數組您必須使用動態分配來更改大小o陣列;優點:你可以通過矢量複用爲功能和訪問他們像這樣:

const int size = 3; 
std::vector<int> V1(10); // Create three vectors of different sizes 
std::vector<int> V2(12); 
std::vector<int> V3(14); 
std::vector<int> *V[size]; // Create an array of 3 vector<int> pointers 
V[0] = &V1; // Set each element to it's corresponding vector 
V[1] = &V2; 
V[2] = &V3; 
for (int i = 0; i < size; i++) { 
    std::cout << V[i]->size() << std::endl; 
} // OUTPUT: 
    // 10 
    // 12 
    // 14 

使用向量的向量(上行:您可以push_back(附加)爲多載體的如你所創建後等):

int size = 3; // Or whatever size you want 
std::vector<std::vector<int>> V(0); 
for (int i = 0; i < size; i++) { 
    V.push_back(std::vector<int>((i+1)*2)); // (0+1)*2; (1+1)*2; (2+2)*2 
} 
for (int i = 0; i < V.size(); i++) { 
    std::cout << V[i].size() << std::endl; 
} // OUTPUT: 
    // 2 
    // 4 
    // 6 

你也可以做一個矢量指針矢量,它可以給你一個矢量的變量大小和從其它地方已經創建的矢量中傳遞的能力。