开发者

Changing object members via an iterator?

开发者 https://www.devze.com 2023-01-30 19:41 出处:网络
Been a while since I\'ve used C++. Can I do something like this?: for (vector<Node>::iterator n = active.begin(); n!=active.end(); ++n) {

Been a while since I've used C++. Can I do something like this?:

for (vector<Node>::iterator n = active.begin(); n!=active.end(); ++n) {
  n->ax /= n->m;
}

where Node is an object with a few floats in it?

If written in Java, what I'm trying to accomplish is something similar to:

for (Node n : this.active) {
  n.ax /=开发者_运维问答 n.m;
}

where active is an arrayList of Node objects.

I think I am forgetting some quirk about passing by reference or something throws hands in the air in desperation


Yes. This syntax basically works for almost all STL containers.

// this will walk it the container from the beginning to the end.
for(container::iterator it = object.begin(); it != object.end(); it++)
{
}

object.begin() - basically gives an iterator the first element of the container.

object.end() - the iterator is set to this value once it has gone through all elements. Note that to check the end we used !=.

operator ++ - Move the iterator to the next element.

Based on the type of container you may have other ways to navigate the iterator (say backwards, randomly to a spot in the container, etc). A good introduction to iterators is here.


Short answer: yes, you can.

The iterator is a proxy for the container element. In some cases the iterator is literally just a pointer to the element.


Your code works fine for me

#include <vector>
using std::vector;
struct Node{
  double ax;
  double m;
};

int main()
{
  vector<Node> active;
  for (vector<Node>::iterator n = active.begin(); n!=active.end(); ++n) {
    n->ax /= n->m;
  }
}


You can safely change an object contained in a container without invalidating iterators (with the associative containers, this applies only to the 'value' part of the element, not the 'key' part).

However, what you might be thinking of is that if you change the container (say by deleting or moving the element), then existing iterators might be invalidated, depending on the container, the operation being performed, and the details of the iterators involved (which is why you aren't allowed to change the 'key' of an object in an associative container - that would necessitate moving the object in the container in the general case).


In the case of std::vector, yes, you can manipulate the object simply by dereferencing the iterator. In the case of sorted containers, such as a std::set, you can't do that. Since a set inserts its elements in order, directly manipulating the contents isn't permitted since it might mess up the ordering.


What you have will work. You can also use one of the many STL algorithms to accomplish the same thing.

std::for_each(active.begin(), active.end(), [](Node &n){ n.ax /= n.m; });
0

精彩评论

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

关注公众号