【发布时间】:2008-12-19 15:25:42
【问题描述】:
简单的问题;什么更好,为什么?
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 = in 建议伙计们 ;)。我正在玩的实际代码是:
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... 里程各不相同。
【问题讨论】:
-
我希望这只是供您个人使用的玩具代码?