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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…