Domanda

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!

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top