我想在C++
這樣來實現insert
:C++如何插入python?
// 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++
使用插入:
// !!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;
}
'詮釋索引= {1,1,2,2 ,3,3,5}'?那......這個代碼是不合格的。 – WhiZTiM
如果你有一個數組,你可以使用['std :: begin'](http://en.cppreference.com/w/cpp/iterator/begin)和['std :: end'](http:// en.cppreference.com/w/cpp/iterator/end)獲取數組的迭代器,並使用[基於範圍的'for'循環](http://en.cppreference.com/w/cpp/language/範圍)或幾乎任何[標準算法函數](http://en.cppreference.com/w/cpp/algorithm)期望由一對迭代器定義的範圍。 –
你的產量和預期產量是多少? –