C ++;迭代结构的向量并访问结构成员

时间:2015-11-23 05:06:02

标签: c++ loops vector struct iterator

我有一个结构:

struct fsobject {
std::string fqname; //Fully Qualified Name of File incl extension
std::string type;   //Type of Object, Either Directory or File
std::string data;   //contents of file. Directories have no data.
};

fsobject类型的向量:

std::vector<fsobject> driveA;//Drive A

我正在尝试迭代向量并访问每个向量元素的struct成员。这是我创建的循环:

for (auto vectorit = driveA.begin(); vectorit != driveA.end(); ++vectorit)
{
    cout << vectorit.fqname <<endl;
}

导致错误:

main.cpp | 50 |错误:'class __gnu_cxx :: __ normal_iterator&gt;'没有名为'fqname'|

的成员

我很难绕过如何完成访问每个vector元素的成员。任何帮助表示赞赏。

以下是完整资料来源:

#include <iostream>
#include <algorithm>
#include <string>
#include <iostream>
#include <list>
#include <cctype>
#include <vector>

struct fsobject {
std::string fqname; //Fully Qualified Name of File incl extension
std::string type;   //Type of Object, Either Directory or File
std::string data;   //contents of file. Directories have no data.
};


using namespace std;

bool compare(const fsobject& first, const fsobject& second)
{
  if (first.fqname < second.fqname)
    return true;
  else
    return false;
}

int main()
{

    std::vector<fsobject> driveA;//Drive A
    std::vector<fsobject> driveB;//Drive B
    std::vector<fsobject> driveC;//Drive C

    driveA.push_back({"/home/zory/","dir",""});
    driveA.push_back({"/home/dory/","dir",""});
    driveA.push_back({"/home/","dir",""});
    driveA.push_back({"/home/anakin/","dir",""});
    driveA.push_back({"/home/luke/","dir",""});
    driveA.push_back({"/home/luke/","dir",""});
    driveA.push_back({"/home/luke/QuaterlyReports.pdf","file","bankruptcy is coming"});

    sort(driveA.begin(),driveA.end(),compare);
    /*cout << driveA.back().fqname << endl;
    driveA.pop_back();
    cout << driveA.back().fqname << endl;*/



    for (auto vectorit = driveA.begin(); vectorit != driveA.end(); ++vectorit)
    {
        cout << vectorit.fqname <<endl;
    }


    cout << "Done...";

    return 0;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

C++ STL Vector Iterator accessing members of an Object

    cout << (*vectorit).fqname;

预期产出的结果。谢谢你的帮助。