Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vector insights

Tags:

c++

stl

vector

I am a little bit frustrated of how to use vectors in C++. I use them widely though I am not exactly certain of how I use them. Below are the questions?

  1. If I have a vector lets say: std::vector<CString> v_strMyVector, with (int)v_strMyVector.size > i can I access the i member: v_strMyVector[i] == "xxxx"; ? (it works, though why?)

  2. Do i always need to define an iterator to acces to go to the beginning of the vector, and lop on its members ?

  3. What is the purpose of an iterator if I have access to all members of the vector directly (see 1)?

Thanks in advance, Sun

like image 309
Sunscreen Avatar asked Mar 06 '26 19:03

Sunscreen


1 Answers

  1. It works only because there's no bounds checking for operator[], for performance reason. Doing so will result in undefined behavior. If you use the safer v_strMyVector.at(i), it will throw an OutOfRange exception.

    It's because the operator[] returns a reference.

  2. Since vectors can be accessed randomly in O(1) time, looping by index or iterator makes no performance difference.

  3. The iterator lets you write an algorithm independent of the container. This iterator pattern is used a lot in the <algorithm> library to allow writing generic code easier, e.g. instead of needing N members for each of the M containers (i.e. writing M*N functions)

    std::vector<T>::find(x)
    std::list<T>::find(x)
    std::deque<T>::find(x)
    ...
    std::vector<T>::count(x)
    std::list<T>::count(x)
    std::deque<T>::count(x)
    ...
    

    we just need N templates

    find(iter_begin, iter_end, x);
    count(iter_begin, iter_end, x);
    ...
    

    and each of the M container provide the iterators, reducing the number of function needed to just M+N.

like image 188
kennytm Avatar answered Mar 08 '26 09:03

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!