我想在C++
中实现insert
,如下所示:
// python code
insertIndexes = [1, 1, 2, 2, 3, 3, 5]
arr = []
toInsertValue = 0;
for i in insertIndexes:
arr.insert(i, toInsertValue)
toInsertValue += 1
print arr // [0, 1, 3, 5, 4, 6, 2]
但是我发现如果我想在C++
中使用insert,我必须知道向量大小:
// !!C++ wrong code!!
// vec is not initialized correctly
vector<int> vec;
int insertIndexes[] = {1, 1, 2, 2, 3, 3, 5}
int toInsertValue = 0;
for (int i = 0; i < sizeof(insertIndexes)/sizeof(insertIndexes[0]); i++) {
vec.insert(vec.begin() + insertIndexes[i], toInsertValue);
toInsertValue += 1;
}
当您定义一个没有特定大小的向量时,它将是空的,并且它的所有索引(有或没有迭代器)都将越界,导致未定义的行为。你知道吗
在循环中,您需要检查
indexes[i]
是否超出范围,如果超出范围,则适当调整向量大小或使用push_back
将值offset
附加到向量。你知道吗在Python中,在列表大小之外的索引处插入是非常宽容的,实现检查插入位置是否大于或等于
len(list)
,然后插入新项。在C++的^ {< CD2> }中,情况并非如此。你得自己检查一下。你知道吗完整示例:
输出(如Coliru直播所示):
相关问题 更多 >
编程相关推荐