簡單的問題;什麼更好,爲什麼?針對調整大小()+迭代器的循環push_back
out.resize(in.size());
T1::iterator outit = out.begin();
for(inIt = in.begin() to end, ++inIt, ++outIt)
*outit = *inIt
OR
out.erase();
for(inIt = in.begin() to end, ++inIt)
out.push_back(inIt);
我假設push_back中隱含的內存分配值得避免,但要確保。
由於
編輯: 感謝您的OUT =在建議球員)。我擺弄實際的代碼是:
template//can't stop the browser ignoring th class T1, class T2 in angle brackets
bool asciihex(T1& out, const T2& in)
{
//out.erase();
out.resize(in.size()/2);
if(std::distance(in.begin(), in.end()) % 2)//use distance rather than size to minimise the requirements on T2?
return false;
for(T2::const_iterator it = in.begin(); it != in.end(); it += 2)
{
out.push_back(((((*it > '9' ? *it - 0x07 : *it) - 0x30) '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f));
}
return true;
}
template
bool asciihex(T1& out, const T2& in)
{
size_t size = in.size();
if(size % 2)//use distance rather than size to minimise the requirements on T2?
return false;
out.resize(size/2);
T1::iterator outit = out.begin();
for(T2::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit)
{
*outit = ((((*it > '9' ? *it - 0x07 : *it) - 0x30) '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f);
}
return true;
}
編輯:我已標記的push_back的答案,因爲它似乎是共識,因此,更給其他人同樣的問題非常有用。然而,我最終使用迭代器方法作爲我感興趣的容器類之一不支持push_back ...里程不同。
我希望這只是供您個人使用的玩具代碼? – Thorsten79 2008-12-29 09:41:39
@ Thorsten79:爲什麼? – Patrick 2008-12-29 12:36:37