简体   繁体   English

向量类型为Struct的向量迭代器错误

[英]Vector Iterator Errors With a Vector of Type Struct

I'm trying to use a vector iterator to print out all of the elements in a vector. 我正在尝试使用向量迭代器来打印出向量中的所有元素。 I've looked up similar questions but the solutions posted don't seem to be working for me. 我查找了类似的问题,但是发布的解决方案似乎对我不起作用。 Here's the code: 这是代码:

void printPerms()
{
   for(vector<process>::iterator it = allProcesses.begin(); it != allProcesses.end(); it++)
   {
      for(int i = 0; i < numResourceTypes; i++)
      {
         cout << (static_cast<process*>(*it).need) << (static_cast<process>(*it)).allocated <<endl;
      }
   }
}

And the errors I am getting, which I don't know how to fix: 和我得到的错误,我不知道如何解决:

error C2440: 'static_cast' : cannot convert from 'process' to 'process *' No user
defined-conversion operator available that can perform this conversion, or the operator
cannot be called

error C2228: left of '.need' must have class/struct/union

Try... 尝试...

void printPerms()
{
   for(vector<process>::iterator it = allProcesses.begin(); it != allProcesses.end(); it++)
   {
      for(int i = 0; i < numResourceTypes; i++)
      {
         cout << it->need << it->allocated << endl;
      }
   }
}

I don't know what exactly is going wrong, nor do I see why you need to use static_cast , however you should be able to access those member variables regardless using the -> operator. 我不知道到底出了什么问题,也不知道为什么需要使用static_cast ,但是无论使用->运算符,您都应该能够访问那些成员变量。

De-referencing an iterator gives you its value (in this case, the process ), with no need for a cast. 取消引用迭代器可为您提供其值(在本例中为process ),而无需进行强制转换。

The problem is that *it is of type process , you might try getting its address before casting by changing 问题是*itprocess类型的,您可以尝试在更改之前通过更改来获取其地址

(static_cast<process*>(*it).need)

to

((static_cast<process*>(&(*it)))->need)

However, it might be simpler to do it->need 但是,这样做可能会更简单- it->need

By the way, if you are just printing (and not modifying the vector contents), then it is recommended to use const_iterator instead of iterator . 顺便说一句,如果您只是打印(而不修改vector内容),那么建议使用const_iterator而不是iterator

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

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