Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

c++ - How can std::vector access elements with huge gaps between them?

Having this code:

template <class IIt, class OIt>
OIt copy2(IIt begin, IIt end, OIt dest)
{
   while (begin != end)
   {
      //make gap between element addresses
      for (int i = 0; i < 99999999; i++)
      {
         dest++;
      }
      *dest++ = *begin++;
   }
   return dest;
}

int main(int argc, char** argv)
{
   vector<int> vec({ 1, 2, 3 });
   vector<int> vec2;
   copy2(vec.begin(), vec.end(), back_inserter(vec2));
   for (int i : vec2)
   {
      cout << i << endl;
   }
}

Which takes quite a long to compile, but will finally do with the proper output

1
2
3

The problem is (without knowing the inner implementation of std::vector, is it c-style array? or more complex structure?), how can it properly find those elements in the for(int i:vec2), when the address (pointers) of those elements are not sequential? (i.e. because of the shifting of the iterator/pointer by 99999999).

I thought there was a requirement for OutputIterator to have that property, that only one-access, one-shift could be performed on it. But when you shift(add) it more than once between accessing them, then there is a gap, which is quite huge in my case. So how does it compile?

question from:https://stackoverflow.com/questions/63196352/how-can-stdvector-access-elements-with-huge-gaps-between-them

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've been fooled.

The iterator returned by std::back_inserter has it++ as a no-op. So those 'gaps' you are creating? Yeah that's all doing nothing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...