我正在从外部API(std :: vector)接收一些整数。C++连接许多std ::向量并删除重复项
API通常需要多次调用,所以我需要将连续API调用中的所有整数累加到本地向量中。最后,数组中的每个元素都必须是唯一的(不需要排序)。
我的代码如下(使用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;
}
如果您想更好地改善工作代码,请在[SE代码审阅](https://codereview.stackexchange.com/)上发布您的问题。 – user0042
另外,如果你需要有一组独特的值,可以使用'std :: set'。 – user0042
你是在[类似这样的](https://ideone.com/usAXuN)? – PaulMcKenzie