2
void max_idxs(vector<int> &pidxs){
   vector<fragment *> ids;
   max_ids(ids);

   for(size_t i = 0; i < ids.size(); i++){
    int weight_idx = ids[i]->weight_idx; //Get weight index
   }
}

In this C++ code, what does it mean by int weight_idx = ids[i]->weight_idx;?

What does -> mean?

Thanks!

ladyfafa
  • 6,629
  • 7
  • 26
  • 22

1 Answers1

17

x->y means (*x).y. In other words, "take the address pointed to by x, and get the variable y from the object there". Here, it means it'll get the weight_idx from the fragment pointed to by ids[i].

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
Borealid
  • 95,191
  • 9
  • 106
  • 122
  • I'd rather say "take the object...", not "take the address...", but that's not enough to prevent me from up-voting you. `:)` – sbi Aug 13 '10 at 17:14
  • sorry, cant know understand the C++ pointer, etc. is it possible not use the "x->y" things? (maintaining the same function) – ladyfafa Aug 13 '10 at 17:20
  • 11
    @ladyfafa if you want to program C++, you will _have_ to understand pointers. – nos Aug 13 '10 at 17:23
  • @ladyfafa, `x->y` is identical to `(*x).y`. You can exchange the two anywhere in your code. – strager Aug 13 '10 at 17:23
  • 5
    @ladyfafa: Unfortunately, in order to understand something like this, you're going to have to understand C++ pointers. There really isn't another equivalent way of doing this. – David Thornley Aug 13 '10 at 17:25
  • 2
    Well, if you for any reason _hate_ the `->` notation, you might do `fragment& f = *ids[i]; f.weight_idx`. – Pedro d'Aquino Aug 13 '10 at 17:26
  • 1
    @ladyfafa, Java has references. If you think of `x` as a reference, then `x->y` is like `x.y` in Java. – strager Aug 13 '10 at 17:28
  • 1
    I wouldn't compare Java references to C++ pointers. C++ pointers are much trickier (but I would argue, more powerful and explicit). – adam_0 Aug 13 '10 at 17:32
  • @adam_0, In this case they are conceptually nearly identical, which is why I stated one in terms of the other. – strager Aug 13 '10 at 18:59
  • @ladyfafa: The problem is not that C++ has pointers, since Java has pointers. The confusing issue is that, in C++, most objects could be either used directly or through a pointer, while in Java there's primitive types (which aren't referenced through pointers) and class types (which are). It's arguable that the C++ `->` is the same as the Java `.`, but in that case there's no Java counterpart to C++'s `.`. – David Thornley Aug 13 '10 at 20:33