C++ STL 向量迭代器访问对象的成员

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/322128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:38:54  来源:igfitidea点击:

C++ STL Vector Iterator accessing members of an Object

c++

提问by richyz

I think I've declared a Vector with an object correctly. But, I don't know how to access it's members when looping with Iterator.

我想我已经正确地声明了一个带有对象的 Vector 。但是,我不知道在使用 Iterator 循环时如何访问它的成员。

In my code, the line --->> cout << " " << *Iter;

在我的代码中,行 --->> cout << " " << *Iter;

How do I print the contents of the members? Like *Iter.m_PackLine ???

如何打印成员的内容?像 *Iter.m_PackLine ???

Not sure if I used the correct terminology, but appreciate the help! Thanks

不确定我是否使用了正确的术语,但感谢您的帮助!谢谢

class CFileInfo
{
  public:
      std::string m_PackLine;
      std::string m_FileDateTime;
      int m_NumDownloads;
};

void main()
{
  CFileInfo packInfo;

  vector<CFileInfo, CFileInfo&> unsortedFiles;
  vector<CFileInfo, CFileInfo&>::iterator Iter;

  packInfo.m_PackLine = "Sample Line 1";
  packInfo.m_FileDateTime = "06/22/2008 04:34";
  packInfo.m_NumDownloads = 0;
  unsortedFiles.push_back(packInfo);

  packInfo.m_PackLine = "Sample Line 2";
  packInfo.m_FileDateTime = "12/05/2007 14:54";
  packInfo.m_NumDownloads = 1;
  unsortedFiles.push_back(packInfo);

 for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ )
 {
    cout << " " << *Iter; // !!! THIS IS WHERE I GET STUMPED
    // How do I output values of the object members? 
 }
}  // end main

回答by Johannes Schaub - litb

cout << " " << *Iter;

will only work if CFileInfohas an overloaded operator<<that can output your struct. You can output individual members of the struct instead like this:

只有当CFileInfo有一个operator<<可以输出你的结构的重载时才会工作。您可以像这样输出结构的各个成员:

cout << " " << Iter->m_PackLine;

Alternatively, the following is equivalent to that:

或者,以下等效于:

cout << " " << (*Iter).m_PackLine;

You have to put parentheses around *Iter, since the member-access operator binds thighter otherwise.

你必须在 *Iter 周围加上括号,否则成员访问运算符会绑定大腿。

On a side-node, make your main function return int instead of void. making it return void is not valid in C++.

在侧节点上,使您的主函数返回 int 而不是 void。使它返回 void 在 C++ 中无效。



You declare the vector like this:

您可以像这样声明向量:

vector<CFileInfo, CFileInfo&> unsortedFiles;

The second argument to vectorshould be another thing. It's not needed for your code to give the vector a second argument at all. Just use this:

的第二个论点vector应该是另一回事。您的代码根本不需要为向量提供第二个参数。只需使用这个:

vector<CFileInfo> unsortedFiles;


Another thing i noticed is you increment the iterator using Iter++(called postfix increment). For iterators, always prefer ++Iter, which is called prefix increment.

我注意到的另一件事是您使用Iter++(称为postfix increment)增加迭代器。对于迭代器,总是喜欢++Iter,它被称为prefix increment

回答by strager

Use (*iter).member or iter->member.

使用 (*iter).member 或 iter->member。

You can also use temporaries:

您还可以使用临时文件:

CFileInfo &fileInfo = *iter;
cout << " " << fileInfo.myMember;

Also, for what you're doing, you'd probably want a const_iterator instead of an (mutable) iterator.

此外,对于您正在做的事情,您可能需要一个 const_iterator 而不是(可变的)迭代器。

In addition, std::vector is a template accepting a typename and an allocator, not two typenames. You can use the default allocator by stripping the second template argument:

此外, std::vector 是一个模板,接受一个类型名和一个分配器,而不是两个类型名。您可以通过剥离第二个模板参数来使用默认分配器:

vector<CFileInfo> unsortedFiles;
vector<CFileInfo>::iterator Iter;


Some nit-picking:

一些挑剔:

  • main should return an int.
  • It'd probably be best to declare your iterator variable in the for statement.
  • It'd probably be faster in run-time performance to use the prefix ++ operator (++iter) instead of the postfix operator (iter++) in your for loop.
  • No need for your comment about main() ending.
  • main 应该返回一个 int。
  • 最好在 for 语句中声明您的迭代器变量。
  • 在 for 循环中使用前缀 ++ 运算符 (++iter) 而不是后缀运算符 (iter++) 可能会提高运行时性能。
  • 无需您对 main() 结束发表评论。

回答by Martin York

First correct you'r vector declaration:

首先更正你的向量声明:

vector<CFileInfo > unsortedFiles;

Next you need to define an output operator for your class:

接下来你需要为你的类定义一个输出操作符:

std::ostream& operator<<(std::ostream& str,CFileInfo const& data)
{
       // Do something here
       /* Potentailly you could do this
        *    But this requires that this function be a friend of the class

       str << data.m_PackLine << ":"
           << data.m_FileDateTime << ":"
           << data.m_NumDownloads << ":";

       *  Or you could do this

           data.print(str);  // Make print a public const method.

       */

       return str;
}

Usually you either make the output operator a friend of your class or provide a public print method that takes a stream. Either way you can then access the members and stream them manually to the output.

通常你要么让输出操作符成为你的类的朋友,要么提供一个接受流的公共打印方法。无论哪种方式,您都可以访问成员并将它们手动流式传输到输出。

Once you have the output iterator defined you can change your loop to use the standard library versions:

定义输出迭代器后,您可以更改循环以使用标准库版本:

std::for_each(unsortedFiles.begin()
              unsortedFiles.end()
              std::ostream_iterator<CFileInfo>(std::cout," ")
             );

回答by orip

iter->m_PackLine

or

或者

(*iter).m_PackLine

回答by Dave

This is the first problem I noticed:

这是我注意到的第一个问题:

std::vectoris a template.

std::vector是一个模板。

You have:

你有:

vector unsortedFiles;

you need something like:

你需要这样的东西:

vector<CFileInfo> unsortedFiles;

Now that I think about it, your template definition may have just gotten parsed out by the stackoverflow comment system.

现在想想,你的模板定义可能刚刚被 stackoverflow 评论系统解析出来了。

回答by richyz

Thanks all, wish I could grant multiple points for the answers :)

谢谢大家,希望我能给答案多分:)

litb also pointed out a problem I was having in my declaration of the vector. I removed the second argument in the vector declaration and it worked.

litb 还指出了我在向量声明中遇到的一个问题。我删除了向量声明中的第二个参数,它起作用了。

Stackoverflow parsed out some of my code, I'll be more careful in posting next time.

Stackoverflow 解析了我的一些代码,下次发帖会小心点。

回答by coppro

vector<CFileInfo, CFileInfo&> will not work at all. The second parameter to vector is the allocator the vector uses, and CFileInfodoes not meet those requirements, nor does any reference type. I think you just want vector<CFileInfo>, the iterators and members will return CFileInfo&automatically.

vector<CFileInfo, CFileInfo&> 根本不起作用。vector 的第二个参数是 vector 使用的分配器,CFileInfo不满足这些要求,也没有任何引用类型。我想你只是想要vector<CFileInfo>,迭代器和成员会CFileInfo&自动返回。