gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
C++ vector get element
- User
C++ vector get element
- Assistant
To get an element from a C++ vector, you can use the
at()function or the overloaded[]operator.The
at()function takes an index as an argument and returns the element at that index. It also performs bounds checking and throws an out_of_range exception if the index is out of bounds.std::vector<int> myVector {1, 2, 3, 4, 5}; int element = myVector.at(2); // returns the element at index 2, which is 3The overloaded
[]operator also takes an index as an argument and returns the element at that index. However, it doesn't perform any bounds checking.std::vector<int> myVector {1, 2, 3, 4, 5}; int element = myVector[2]; // returns the element at index 2, which is 3Both methods are commonly used, but it's recommended to use
at()if you're not sure whether the index is in bounds or not to avoid runtime errors.