繁体   English   中英

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

[英]direct accessing array of vectors in a 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

           }
    }

为什么您认为“ 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中不会获得重大收益。

#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;
    }


}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM