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 ( 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

           }
    }
4

2 回答 2

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 没有重大收益。

于 2013-10-20T20:28:54.337 回答
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;
    }


}
于 2013-10-20T21:12:48.297 回答