簡體   English   中英

向量類型為Struct的向量迭代器錯誤

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

我正在嘗試使用向量迭代器來打印出向量中的所有元素。 我查找了類似的問題,但是發布的解決方案似乎對我不起作用。 這是代碼:

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

和我得到的錯誤,我不知道如何解決:

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

嘗試...

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

我不知道到底出了什么問題,也不知道為什么需要使用static_cast ,但是無論使用->運算符,您都應該能夠訪問那些成員變量。

取消引用迭代器可為您提供其值(在本例中為process ),而無需進行強制轉換。

問題是*itprocess類型的,您可以嘗試在更改之前通過更改來獲取其地址

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

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

但是,這樣做可能會更簡單- it->need

順便說一句,如果您只是打印(而不修改vector內容),那么建議使用const_iterator而不是iterator

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM