开发者

getting object in each element in vector

开发者 https://www.devze.com 2023-03-28 00:50 出处:网络
Is there a way for an iterator to return an object in each element of a C++ Standard Library vector? I have this code:

Is there a way for an iterator to return an object in each element of a C++ Standard Library vector?

I have this code:

struct mystruct {
  int field1;
}

int DoSomethingWithMyStruct(mystruct& a);

std::vector<mystruct> myVector;
std::vector<mystruct&开发者_高级运维gt;::iterator it;

mystruct s1,s2, temp;
s1.field1=1;
s2.field1=2;

for (it=myVector.begin();it!=myVector.end();it++)
{
   //I want to call DoSomethingWithMyStruct, so I have to pass in mystruct object.
   //can I use iterator to get the object of each element in myVector without having to create a temporary mystruct object and pass it in?
   //I'm looking for an easier way than having to do this:
   temp.field1 = it->field1;
   DoSomethingWithMyStruct(temp);

}


As well as what the others said, you can do this instead:

#include <algorithm>

std::for_each(myVector.begin(), myVector.end(), DoSomethingWithMyStruct);

It's short and succinct. No need of manual loop.


Yes:

DoSomethingWithMyStruct(*it);


Just dereference the iterator, surely:

std::vector<mystruct>::iterator it, end;
for (it = myVector.begin(), end = myVector.end(); it != end; ++it) {
   DoSomethingWithMyStruct(*it);
}

Or am I missing something here...?

Going further, there are other ways to iterate. You could use BOOST_FOREACH or C++0x ranged-for to simplify the loop. You could also use an algorithm like std::for_each to remove it entirely!


(Remember that it->field1 is like (*it).field1, so you're already doing this... even though you're going on to make your code more complicated than is necessary afterwards!)


Just simply dereference your iterator. *it, and you get a mystruct. They behave like pointers in this regard.

But in the case if you wonder how to iterate over all fields of all elements of a vector, where the elements are polymorphic; e.g. std::vector<Base*>, it's a bit more difficult. Since C++ doesn't have reflection that would make this possible (semi)automatically, you need to do it manually. Something similar to the Visitor Pattern comes to mind.


  1. You have not populated myVector
  2. Could make code more efficent like this

    std::vector<mystruct>::const_iterator theEnd;

    for (it=myVector.begin();it!=theEnd;++it)

    Notice the position of the ++

  3. I think that &(*it) should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消