C++如何插入Python?

2024-09-27 01:27:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在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;
}

Tags: inforisnotcode向量intinsert
2条回答

当您定义一个没有特定大小的向量时,它将是空的,并且它的所有索引(有或没有迭代器)都将越界,导致未定义的行为。你知道吗

在循环中,您需要检查indexes[i]是否超出范围,如果超出范围,则适当调整向量大小或使用push_back将值offset附加到向量。你知道吗

在Python中,在列表大小之外的索引处插入是非常宽容的,实现检查插入位置是否大于或等于len(list),然后插入新项。在C++的^ {< CD2> }中,情况并非如此。你得自己检查一下。你知道吗

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 

相关问题 更多 >

    热门问题