这最初是对问题的编辑。用户 cigien 建议将其发布为答案。这包含一些不完整(即尚未探索实施解决方案的所有可能性)的分析结果。
我做了一些分析代码(我绝不是分析专家)比较我的版本和 Cory Kramer 的答案。答案中的代码似乎比我的快 4.5 倍(在quick-bench.com 使用 GCCv10.1、C++17、O3 优化进行了测试)。 Remy Lebeau 建议保存一个临时的迭代器似乎没有任何区别。
在问自己之前,我错过了一些重复的问题:1 和 2。其中的一些答案提出了更细微的不同解决方案,我尚未对此进行分析。
range-v3 库(由 cigien 回答)虽然看起来很方便,但不是我可以使用的选项,我也没有对其进行分析。
分析代码:
// This code is intended to be used at quick-bench.com.
// Needs profiling library AND ADDITIONAL INCLUDES to compile,
// see https://github.com/google/benchmark
#include<vector>
template<typename T>
std::vector<T> repeat_1(const std::vector<T> &input, unsigned int times) {
std::vector<T> result;
auto input_size = input.size();
result.reserve(input_size * times);
for (std::size_t rep = 0; rep < times; ++rep) {
for (std::size_t i = 0; i < input_size; ++i) {
result.push_back(input[i % input_size]);
}
}
return result;
}
template<typename T>
std::vector<T> repeat_2(const std::vector<T> &input, unsigned int times) {
std::vector<T> result(input.size() * times);
for (std::size_t rep = 0; rep < times; ++rep) {
std::copy(input.begin(), input.end(),
std::next(result.begin(), rep * input.size()));
}
return result;
}
template<typename T>
std::vector<T> repeat_3(const std::vector<T> &input, unsigned int times) {
std::vector<T> result(input.size() * times);
auto iter = result.begin();
for (std::size_t rep = 0; rep < times; ++rep, iter += input.size()) {
std::copy(input.begin(), input.end(), iter);
}
return result;
}
static void version_1(benchmark::State &state) {
std::vector<int> vec = {12, 4, 4, 5, 16, 6, 6, 17, 77, 8, 54};
for (int i = 0; i < 100'000; ++i) {
vec.push_back(i % 10'000);
}
for (auto _ : state) {
auto repeated = repeat_1(vec, 1000);
// Make sure the variable is not optimized away by compiler
benchmark::DoNotOptimize(repeated);
}
}
BENCHMARK(version_1);
static void version_2(benchmark::State &state) {
std::vector<int> vec = {12, 4, 4, 5, 16, 6, 6, 17, 77, 8, 54};
for (int i = 0; i < 100'000; ++i) {
vec.push_back(i % 10'000);
}
for (auto _ : state) {
auto repeated = repeat_2(vec, 1000);
// Make sure the variable is not optimized away by compiler
benchmark::DoNotOptimize(repeated);
}
}
BENCHMARK(version_2);
static void version_3(benchmark::State &state) {
std::vector<int> vec = {12, 4, 4, 5, 16, 6, 6, 17, 77, 8, 54};
for (int i = 0; i < 100'000; ++i) {
vec.push_back(i % 10'000);
}
for (auto _ : state) {
auto repeated = repeat_3(vec, 1000);
// Make sure the variable is not optimized away by compiler
benchmark::DoNotOptimize(repeated);
}
}
BENCHMARK(version_3);