문제

As per Mark Ransoms answer on using memset, i am using memset on a vector<int> to assign values to all the elements.

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

It does have a significant performance improvement over std::fill and it works fine(g++ 4.3.2, 64bit linux). Is this code safe , as in , would std::vector implementations always guarantee that memory allocation for the data will be contiguous? Is it possible that in a future(or different) implementation of the stl library that this might change and break my code later?

도움이 되었습니까?

해결책

would std::vector implementations always guarantee that memory allocation for the data will be contiguous

Yes. 23.3.6.1/1. In C++03 standard there are equal strings at 23.2.4/1

The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size()

Is it possible that in a future(or different) implementation of the stl library that this might change and break my code later?

No. Vector should be contiguous always.

However, in gcc 4.6.3 there is only one optimization of fill, 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);
    }

다른 팁

This should be safe from a memory perspective.

Just bear in mind that if the content of your vector is not a plain data type, you shouldn't be doing this sort of thing.

memset fails with vector of bool type, just try below example, though as other mentioned it work for other plain data type.I shared it just to make it explicit its not true for all plain 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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top