我看到以下代码用于从以下位置删除一个选定的元素std::vector:
vector<hgCoord>::iterator it;
int iIndex = 0;
const int iSelected = 5;
for( it = vecPoints.begin(); it != vecPoints.end(); ++it, ++iIndex )
{
if( iIndex == iSelected )
{
vecPoints.erase( it );
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这段代码效率不高,应该写成如下:
vector<hgCoord>::iterator it;
int iIndex = 0;
const int iSelected = 5; // we assume the vector has more than 5 elements.
vecPoints.erase( vecPoints.begin() + iSelected );
Run Code Online (Sandbox Code Playgroud)
但是,我不确定此代码是否遵循C++ STL标准.
Kon*_*lph 12
要使此代码具有通用性,因此无论迭代器是否支持operator +,它都可以工作,并使用最有效的可用实现:
template <typename C>
void erase_at(C& container, typename C::size_type index) {
typename C::iterator i = container.begin();
std::advance(i, index);
container.erase(i);
}
Run Code Online (Sandbox Code Playgroud)
在内部,如果迭代器类型支持它,则std::advance使用operator +它.否则(例如for std::list<>::iterator)它会在循环中一次一步地推进迭代器,就像你发布的第一个代码一样.
| 归档时间: |
|
| 查看次数: |
258 次 |
| 最近记录: |