Memset on vector <int>

To Mark Ransoms answer when using memset, I use memset for vector<int> to assign values ​​to all elements.

 memset(&match_begin[0], 0xff , sizeof(match_begin[0]) * match_begin.size()); 

This has a significant performance improvement over std::fill , and it works great (g ++ 4.3.2, 64-bit Linux). Is this code safe, as in, does the implementation of std :: vector always ensure that the memory allocation for the data is contiguous? Is it possible that in a future (or other) implementation of the stl library this could change and break my code later?

+4
source share
3 answers

the std :: vector implementation always ensures that the memory allocation for the data is contiguous

Yes. 23.3.6.1/1 . In the C ++ 03 standard there are equal lines in 23.2.4 / 1

The elements of the vector are stored adjacent , which means that if v is a vector, where T is some type other than bool, then it obeys the identifier & v [n] == & v [0] + n for all 0 <= n <V. SIZE ()

Is it possible that in a future (or other) implementation of stl, that this could change and break my code later?

No. A vector must always be contiguous.

However, in gcc 4.6.3 there is only one fill optimization using memset. This optimization is for char types

  // Specialization: for char types we can use memset. template<typename _Tp> inline typename __gnu_cxx::__enable_if<__is_byte<_Tp>::__value, void>::__type __fill_a(_Tp* __first, _Tp* __last, const _Tp& __c) { const _Tp __tmp = __c; __builtin_memset(__first, static_cast<unsigned char>(__tmp), __last - __first); } 
+4
source

This should be safe in terms of memory.

Just keep in mind that if the contents of your vector is not a simple data type, you should not do this kind of thing.

+1
source

memset fails with a vector like bool, just try the example below, although as mentioned earlier, it works for another simple data type. I just shared it so that it is clearly not valid for all simple data types.

 #include <vector> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<bool>vec; vec.push_back(0); vec.push_back(1); memset(&vec[0], 0, sizeof(vec[0]) * vec.size()); return 0; } 
+1
source

All Articles