0

I have the following code snippet:

struct compare {
    bool operator()(const pair<size_t, double>& left, const pair<size_t, double>& right) {
               return left.second > right.second;
    }
};

int main() {
   size_t vertices = 31112738;
   vector<pair<size_t, double> > opt, one;
   opt.reserve(vertices);
   one.reserve(vertices);

   for(size_t i=0;i<vertices;i++) {
      opt[i] = make_pair(i,rand());
      one[i] = make_pair(i,rand()); 
   }

   sort(opt.begin(), opt.end(), compare());
   sort(one.begin(), one.end(), compare());

  return 0;


}

Even after calling the sort function, opt[] and one[] aren't sorted. If however I use push_back() to insert the elements and then call the sort() function, they get sorted.

Why is the outcome different in the two scenarios?

user1715122
  • 947
  • 1
  • 11
  • 26

1 Answers1

2

Because in the scenario you outlined, the vectors always have size 0.

You reserve more space in the vectors, but you never resize them. (So your for-loop just triggers undefined behavior by writing past the end of the vectors)

push_back grows the vector's size by 1, but if you don't call that, then you must call resize and set the size explicitly. (or specify the size as a constructor argument)

jalf
  • 243,077
  • 51
  • 345
  • 550
  • I didn't understand. So after I reserve the space, how do I access it? So I cannot insert at a random position? – user1715122 Oct 02 '13 at 07:14
  • @user1715122 You may want to read about the [`resize`](http://en.cppreference.com/w/cpp/container/vector/resize) method. – Some programmer dude Oct 02 '13 at 07:19
  • because if I print out the values of opt[] or one[] from, say index '0' to '9', they aren't '0'. Are you saying they are garbage values? – user1715122 Oct 02 '13 at 07:20
  • 1
    @user1715122 yes. If the vector has size `n`, then it only promises that the first `n` indices are valid. Anything beyond that is *undefined*. Trying to access element `n+1` might still compile, but it is undefined behavior, and what it contains will likely be arbitrary garbage. But more importantly for your specific case, `end()` returns an iterator pointing to the end of the vector. If it has size 0, then it doesn't care that you tried to write something into the 8th index, because the end of the vector is still right at the beginning. – jalf Oct 02 '13 at 07:58