1

I have a std::vector<char*> that I want to copy into a std::vector<MemRef>, in a performance-critical section. I've looked at solutions using std::copy(), boost::make_transform_iterator, std::vector<int> newVec; newVec.reserve(oldVec.size()); .. push_back() and I have no idea what's best.

MemRef is a small object containing a char* and a size_t length.

I'm using GCC 4.4.7 with --std=g++0x so I get some c++ features, including emplace_back() which is nice for avoiding constructors and copying.

I think I'm better off not constructing the vector afresh each time, but rather using the vector clear() method to empty it, which as I understand allows it to refill to capacity without reallocation.

I'd appreciate help getting my head around this!

Chap
  • 3,649
  • 2
  • 46
  • 84

1 Answers1

1

I think std::copy would have pretty good performance, especially with the one note I see on cppreference.com

In practice, implementations of std::copy avoid multiple assignments and use bulk copy functions such as std::memmove if the value type is TriviallyCopyable

If the types require conversion then I would do this:

class MemRef
{
  public:
    MemRef(char * astr) : ptr_( astr), size_( strlen( astr)) { }
...
} ;

vecMem.insert(vecMem.end(), cstrVec.begin(), cstrVec.end()) ;

This allows vecMem to figure out how much space it needs to reserve in one go.

woolstar
  • 5,063
  • 20
  • 31
  • Please correct URL (algorithm/copy). SO won't allow "trivial edits. – Chap Dec 04 '13 at 03:31
  • This is as good a place to start as any, although I can't imagine bulk copy coming into play when each element must be converted. – Chap Dec 04 '13 at 03:37
  • I didn't know if you already had an automatic conversion between the types. I have my own type similar to your `MemRef` that has a constructor that takes a `const char *` – woolstar Dec 04 '13 at 04:01