【问题标题】:Remove a Chunk of Items from a Vector? [duplicate]从向量中删除一大块项目? [复制]
【发布时间】:2022-01-19 01:34:19
【问题描述】:

我有一个充满单词的向量,我试图在指定的开头和结尾擦除该向量的一部分。例如:

#include <string>
#include <vector>

int main() {
    std::vector<std::string> words = { "The", "Quick", "Brown", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" };
    remove_chunk(words, 1, 2);
}

这里,remove_chunk(words, 1, 2); 将删除索引 1 到 2 处的项目,留下向量:

{ "The", "Fox", "Jumps", "Over", "The", "Lazy", "Dog" }

我将如何高效地编写remove_chunk?是否有 stl 功能或快速单线?

【问题讨论】:

标签: c++ vector erase


【解决方案1】:

使用vector::erase:

words.erase(words.begin(), words.begin() + 2);

注意:提供的第二个迭代器是 words.begin() + 2 而不是 words.begin() + 1,因为 STL 使用 [begin, end)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多