2017-02-13 56 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