Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· openaiHugging Face Suzhen/CodeChat

C++ vector get element

  1. User

    C++ vector get element

  2. 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 3
    

    The 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 3
    

    Both 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.