Vector at()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 51423benam
    New Member
    • Apr 2018
    • 31

    Vector at()

    Hello,

    in my program I use vectors, and I get a segfault. I use gcc on windows 10 x64. I could reproduce it with a test file:
    Code:
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        cout << "Hello world!" << endl;
        std::vector<int> tvec = vector<int>();
        tvec.reserve(256);
        for(int counter = 0; counter < 256; counter++){
            tvec->at(counter) = 0;
        }
        return 0;
    }
    Does somebody know why I get a sagfault? Did I miss something in vectors behaviour?
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    When you declare:

    Code:
    vector<int> tvec;

    the number of elements is 0. So using the "at" member function won't work because there are no elements set up.


    Instead you use push_back. After you push_back there is an element and you can use "at" on it.


    When you declare:

    Code:
    vector<int> tvec;
    tvec.reserve(256);
    memory is allocated for 256 elements but no elements are in the vector. The "at" crashes again for the reason above.



    To get 256 elements which are initialized as elements you declare:

    Code:
    vector<int> tvec(256);
    Since the elements are in the vector, the "at" works the first time.

    Comment

    • 51423benam
      New Member
      • Apr 2018
      • 31

      #3
      So if I understand it correctly now: The reserve() still needs push_backs to fill the vector, but it takes care that the vector doesn't need to reallocate until I made 256 push_backs right?

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        That's correct.

        On that subject, when you declare vector<int> tvec as a local variable, do not assume the vector is on the stack. Most of the designs I have seen will keep the first 20-30 items on the stack and after that, the vector moves to the heap. So creating the vector on the heap is really a waste of time. You need do nothing to manage the vector memory.

        Comment

        Working...