2017-02-13 49 views
-1

我想在C++這樣來實現insertC++如何插入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; 
} 
+3

'詮釋索引= {1,1,2,2 ,3,3,5}'?那......這個代碼是不合格的。 – WhiZTiM

+0

如果你有一個數組,你可以使用['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)期望由一對迭代器定義的範圍。 –

+0

你的產量和預期產量是多少? –

回答

2

在Python中,在列表大小以外的索引處插入非常容易,實現會檢查插入位置是否大於或等於len(list),然後插入新項目。在C++的std::vector中,情況並非如此。你必須自己檢查一下。

auto offset = 0; 
for(auto x : indexes){ 
    if(x < vec.size())  //Is the selected index in range? 
     vec.insert(vec.begin() + x, offset++); 
    else 
     vec.insert(vec.end(), offset++);    
} 

完整例如:

std::vector<int> indexes = {1, 1, 2, 2, 3, 3, 5}; 
std::vector<int> vec; 

auto offset = 0; 
for(auto x : indexes){ 
    auto iter = (x < int(vec.size())) ? vec.begin() + x : vec.end(); 
    vec.insert(iter, offset++); 
} 

std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " ")); 

輸出(作爲活看到的Coliru):

0 1 3 5 4 6 2 
+0

so so sorry,我只是在Python代碼中犯了錯誤,我想要的是這樣的:http://coliru.stacked -crooked.com/a/6bd0cb40dbf9ddb2 – roger

+0

@roger,好的。在那裏,你甚至有它。 。 : - )...我希望這已經回答了你的問題,你的問題解決了嗎? – WhiZTiM

0

當你定義一個矢量沒有特定的大小,它將是空的和所有索引到它(有或沒有迭代器)將是越界導致未定義的行爲r

在你的循環中,你需要檢查indexes[i]將不會超出範圍,如果它然後適當調整矢量大小或使用push_back將值offset附加到該矢量。

+0

我想你誤會了我, so sorry – roger

+0

@roger想一想:如果vector是空的(最初是這樣),那麼'vec.begin()'爲迭代器返回什麼?它返回'vec.end()'!你首先要做的事情是循環嗎?你想插入一個元素在位置'vec.end()+ 1',這是超出界限。 –

+0

是的我知道我的代碼 – roger