0

Currently, I access my vector of structs like so:

v_some_vector[some_position].name
v_some_vector[some_position].age
v_some_vector[some_position].etc

What I want to do:

s = v_some_vector[some_position];
s.name
s.age
s.etc

Any info on how I can do this is appreciated.

  • 1
    It would be better to use a reference, but keep in mind anything that causes the vector to resize like adding or removing elements can invalidate references or pointers to elements. `auto& s = s = v_some_vector[some_position];` If you used a pointer you would need to use `->` to access members, not `.`. – Retired Ninja Aug 10 '22 at 00:11
  • This actually has been my problem for the past two hours. I kind of just glazed over "resizing vector could..." I suppose I'll just keep the somewhat clunky vector[index] dot access. I do resize the vector often, and was losing the reference, thank you. – Baddy Nasty Aug 10 '22 at 02:43
  • Definitely best used for something temporary, like a short cut to save some typing and make code more readable. – Retired Ninja Aug 10 '22 at 02:48

2 Answers2

3

C++ has two forms of indirection: Pointers and references. In the shown example, using reference is more appropriate. An example:

auto& s = v_some_vector[some_position];
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • I see, thankyou both! I need to figure out how a pointer is different than a reference. – Baddy Nasty Aug 10 '22 at 00:15
  • 2
    @BaddyNasty -- no need to figure out anything, you should find plenty of explanations for that in your C++ textbook; is there something there that's unclear to you? – Sam Varshavchik Aug 10 '22 at 00:20
  • Hmm, did some googling. A pointer is a memory address? I guess I'm unsure what situations I would need an address opposed to a variable (or an object?) reference. – Baddy Nasty Aug 10 '22 at 00:23
  • A pointer is a variable that contains an address for an object. A reference is an alias (alternative name of) an object. Obviously, there's a relationship between the two, when the pointer contains the address of an object, and the reference refers to the same object. But the usage of them has syntactic and other differences. – Peter Aug 10 '22 at 00:31
  • 1
    @BaddyNasty: I strongly suggest that you learn C++ from [a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) (Beginner's level) instead of from Google. – Andreas Wenzel Aug 10 '22 at 00:42
  • I appreciate it guys. I will look into getting an intro book as well. – Baddy Nasty Aug 10 '22 at 00:59
0

Alternatively, you could put whatever you want to do in a separate function

void foo(S s) {
  s.name...
  s.age
  s.etc
}

and call it with your vector's element:

foo(v_some_vector[some_position]);
Vlad Feinstein
  • 10,960
  • 1
  • 12
  • 27