C++ 连接许多 std::vectors 并删除重复项

标签 c++ c++11 vector

我正在从外部 API (std::vector) 接收一些整数。

API 通常需要多次调用,因此我需要将连续 API 调用的所有整数累加到一个局部 vector 中。最后,数组的每个元素都必须是唯一的(不需要排序)。

我的代码如下(使用 getNextVector 来“模拟”数据并模拟 API 调用)。

该代码有效,但我希望此操作具有最高性能。我的方法正确吗?

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

std::vector<int> getNextVector(int i) {
    if ( i == 0 ) {
        std::vector<int> v = { 1,2,3 };
        return v; 
    } else if ( i == 1 ) {
        std::vector<int> v = { 3,4,5 };
        return v; 
    } else if ( i == 2 ) {
        std::vector<int> v = { 5,6,7 };
        return v; 
    } else if ( i == 3 ) {
        std::vector<int> v = { 7,8,9 };
        return v; 
    }
}

int count() { return 4; } //we have four vectors

int main(int argc, char** argv) {

    std::vector<int> dest;
    dest.reserve(20); // we can find this, for simplicity hardcode...

    for( int i = 0; i < count(); i++ ) {
        std::vector<int> src = getNextVector(i);
        dest.insert(
            dest.end(),
            std::make_move_iterator(src.begin()),
            std::make_move_iterator(src.end())
        );
    }

    std::sort(dest.begin(), dest.end());
    dest.erase(unique(dest.begin(), dest.end()), dest.end());
/*
    std::copy(
      dest.begin(),
      dest.end(),
      std::ostream_iterator<int>(std::cout, "\n")
    );
*/
    return 0;
}

最佳答案

我认为您可以将 vector 的元素存储在一个集合中。如果不需要排序,您可以使用 unordered_set。只需执行以下操作 -

std::unordered_set<int> integers;

for (int i = 0; i < count; i++) {
    std::vector<int> src = getNextVector(i);

    for (int j = 0; j < src.size(); j++) {
        integers.insert(src[i]);
    }
}

或者按照@StoryTeller 的建议,您可以使用适当的函数代替循环。例如 -

std::unordered_set<int> integers;

for (int i = 0; i < count; i++) {
    std::vector<int> src = getNextVector(i);
    integers.insert(src.begin(), src.end());
}

关于C++ 连接许多 std::vectors 并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46262210/

相关文章:

c++ - Linux g++ 在 C++ 中嵌入 Prolog 逻辑引擎

c++ - 出现 bad_alloc 错误

c++ - 如果我们在不同的机器上将 c++11 mt19937 作为相同的种子,我们会得到相同的随机数序列吗

c++ - B. Stroutstrup 在他的新书 "incautious use"第 4 版的第 296 页上的这一段中用表达式 "TCPL"指的是什么?

c++ - 为什么 C++ 不能在不让我们编写标记的情况下自动确定何时使用 constexpr?

c++ - 根据这些对象的属性值对指向对象的指针 vector 进行排序

c++ - 用 t 个随机数生成位 vector

c++ - 编译器或 boost 库的错误?

c++ - C 风格的字符串

c++ - 另一个 : Passing Vector of Structs to Function - C++, MinGW