2013-10-20 34 views
0

我有幾個向量被保存在一個向量中。我必須對它們執行某些邏輯操作,如果操作成功完成,我必須存儲保存在arrayOfUsers中的該向量。問題是我無法訪問arrayOfusers中存儲的特定向量直接訪問向量中的向量陣列

示例:arrayOfUsers有3個向量存儲在其中,它通過了邏輯操作,我必須將向量編號2寫入文件中。我不能索引中arrayOfUsers

vector<string> usersA ("smith","peter"); 
    vector<string> usersB ("bill","jack"); 
    vector<string> usersC ("emma","ashley"); 


    vector<vector<string>> arrayOfUsers; 

    arrayOfUsers.push_back(usersA); 
    arrayOfUsers.push_back(usersB); 
    arrayOfUsers.push_back(usersC); 

我的for循環

for (auto x=arrayOfUsers.begin(); x!=arrayOfUsers.end(); ++x) 
    { 

    for (auto y=x->begin(); y!=x->end(); ++y) 

     { 

       //logic operations 
     } 

      if(logicOperationPassed== true) 
      { 
       // i cannot access the vector here, which is being pointed by y 
       //write to file the vector which passed its logic operation 
       // i cannot access x which is pointed to the arrayOfUsers 

       // ASSUMING that the operations have just passed on vector index 2, 
       //I cannot access it here so to write it on a file, if i dont write 
       //it here, it will perform the operations on vector 3 

      } 
    } 
+1

因爲它的內部爲for循環 – meWantToLearn

+0

當'logicOperationPassed'變爲'true'保存值'y'在另一個變量的內部for循環 – P0W

回答

0

運行直接訪問矢量爲什麼你認爲的「Y」矢量指向?看起來它應該指向一個字符串。

x是「arrayOfUsers」中的一個元素,y是其中一個元素。

FWIW - 你似乎正在使用一些C++ 11功能(自動),而不是所有的方式。爲什麼不一樣的東西:

string saved_user; 
for (const vector<string>& users : arrayOfUsers) { 
    for (const string& user : users) { 
    ... 
    ... Logic Operations and maybe saved_user = user ... 
    } 
    // If you need access to user outside of that loop, use saved_user to get to 
    // it. If you need to modify it in place, make saved_user a string* and do 
    // saved_user = &user. You'll also need to drop the consts. 
} 

的命名會爲你處理與各級什麼清晰,類型是微不足道的,從汽車所以沒有大的漲幅。

0
#include <iostream> 
#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 
    vector<string> usersA; 
    vector<string> usersB; 
    vector<string> usersC; 

    usersA.push_back("Michael"); 
    usersA.push_back("Jackson"); 

    usersB.push_back("John"); 
    usersB.push_back("Lenon"); 

    usersC.push_back("Celine"); 
    usersC.push_back("Dion"); 

    vector <vector <string > > v; 
    v.push_back(usersA); 
    v.push_back(usersB); 
    v.push_back(usersC); 

    for (vector <vector <string > >::iterator it = v.begin(); it != v.end(); ++it) { 
     vector<string> v = *it; 
     for (vector<string>::iterator it2 = v.begin(); it2 != v.end(); ++it2) { 
      cout << *it2 << " "; 
     } 
     cout << endl; 
    } 


}