在向列表添加项目时如何遍历列表

nat*_*yer 5 c++ vector

我有一个线段列表(std::vector<std::pair<int, int> >我想对其进行迭代和细分。该算法将以psuedocode表示:

for segment in vectorOfSegments:
    firstPoint = segment.first;
    secondPoint = segment.second;
    newMidPoint = (firstPoint + secondPoint) / 2.0
    vectorOfSegments.remove(segment);
    vectorOfSegments.push_back(std::make_pair(firstPoint, newMidPoint));
    vectorOfSegments.push_back(std::make_pair(newMidPoint, secondPoint));
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是如何push_back在不永久遍历此列表的情况下如何添加新元素(并删除旧元素)。

似乎最好的方法可能是首先创建此向量的副本,然后将该副本用作参考,clear()原始向量,然后push_back将新元素用作最近清空的向量。

有更好的方法吗?

Lig*_*ica 3

看起来最好的方法可能是首先复制这个向量,并使用副本作为参考,clear()原始向量,然后将新元素push_back到最近清空的向量。

几乎。您不需要复制并清除;改为移动

// Move data from `vectorOfSegments` into new vector `original`.
// This is an O(1) operation that more than likely just swaps
// two pointers.
std::vector<std::pair<int, int>> original{std::move(vectorOfSegments)};

// Original vector is now in "a valid but unspecified state".
// Let's run `clear()` to get it into a specified state, BUT
// all its elements have already been moved! So this should be
// extremely cheap if not a no-op.
vectorOfSegments.clear();

// We expect twice as many elements to be added to `vectorOfSegments`
// as it had before. Let's reserve some space for them to get
// optimal behaviour.
vectorOfSegments.reserve(original.size() * 2);

// Now iterate over `original`, adding to `vectorOfSegments`...
Run Code Online (Sandbox Code Playgroud)