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.

3
  • 2
    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 .. Commented Aug 10, 2022 at 0: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. Commented Aug 10, 2022 at 2:43
  • Definitely best used for something temporary, like a short cut to save some typing and make code more readable. Commented Aug 10, 2022 at 2:48

2 Answers 2

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];
Sign up to request clarification or add additional context in comments.

6 Comments

I see, thankyou both! I need to figure out how a pointer is different than a reference.
@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?
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.
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.
@BaddyNasty: I strongly suggest that you learn C++ from a good book (Beginner's level) instead of from Google.
|
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]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.