How to adjust vector iterator to return struct?

2019-07-24 23:52发布

As a part of my ongoing task of converting a C++ project from Unix to Linux, I now have the following error:

jh205.C: In member function ‘FVSearchLogical_t* FVLogical::getFirst(long int)’: jh205.C:9615: error: invalid cast from type ‘__gnu_cxx::__normal_iterator > >’ to type ‘FVSearchLogical_t*’ jh205.C: In member function ‘FVSearchLogical_t* FVLogical::getNext(long int)’: jh205.C:9630: error: cannot convert ‘__gnu_cxx::__normal_iterator > >’ to ‘FVSearchLogical_t*’ in return jh205.C: In member function ‘void FVLogical::updateTable()’: jh205.C:9656: error: invalid cast from type ‘__gnu_cxx::__normal_iterator > >’ to type ‘void*’

It comes from this code:

FVSearchLogical_t * FVLogical::getFirst(long sensorId) {

  // loop through the Search vector to find the first one for the sensor
  m_searchLogical_it =  m_FVSearchVector.begin();
  for(int i=0; i < m_FVSearchVector.size(); i++){

    // as soon as we find the first one return it
    if(m_searchLogical_it->ml_sensorId == sensorId) {
      return m_searchLogical_it;
    }
    m_searchLogical_it++;
  }

  return NULL;
}

The struct it is about:

typedef struct {
    long ml_sensorId;
    char mc_startDate[10];
    char mc_startTime[10];
    char mc_endDate[10];
    char mc_endTime[10];
    long ml_startBlk;
    long ml_endBlk;
    long ml_sendUnit;
} FVSearchLogical_t;

Any suggestions on how to do this with the least amount of code changes in the project?

Added information:

FVLogical::~FVLogical(){
  m_FVSearchVector.clear();
  m_FVInsertVector.clear();
  m_rptDataVector.clear();
  m_rptHeaderVector.clear();
  m_rptFooterVector.clear();
}

1条回答
Rolldiameter
2楼-- · 2019-07-25 00:24

You are trying to return an iterator exactly as the warning says you are in the line:

return m_searchLogical_it;

To get a raw pointer to the element, which is the return type of getFirst, you'll need to get a pointer to the object m_searchLogical_it points to. To do that you'll need to dereference the iterator to get the object, then take the address of the object:

return &*m_serchLogical_it;

If I may additionally suggest; you're using an iterator (m_searchLogical_it) and a loop counter (i), when all you need to use is the iterator:

for(m_searchLogical_it = begin(m_FVSearchVector); m_searchLogical_it != end(m_FVSearchVector); ++m_searchLogical_it) {
    if(m_searchLogical_it->ml_sensorId == sensorId) {
        return &*m_searchLogical_it;
    }
}
查看更多
登录 后发表回答