直接访问向量中的向量数组

时间:2013-10-20 20:11:47

标签: c++ vector

我有几个向量保存在向量中。我必须对它们进行某些逻辑运算,如果操作成功完成,我必须存储保存在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 ( 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

           }
    }

2 个答案:

答案 0 :(得分: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.
}

关于你在每个级别处理什么,命名会更清楚,而且类型很简单,所以auto不会有重大收益。

答案 1 :(得分: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;
    }


}
相关问题