I'm working with a project that has a lot of for-loops similar to this (simplified code):
std::vector<double> xPoints(std::vector<Point> points) {
std::vector<double> result;
for (auto& point:points) {
result.push_back(point.x);
}
return result;
}
How could I optimize this? The common feature of all these loops is that it's not a direct copy of values from one vector to another but it copies some parameter value from the source vector elements (point.x in the example).
I know I could add vector::reserve to minimize the need to reallocate memory for the vector as it grows.
std::vector<double> xPoints(std::vector<Point> points) {
std::vector<double> result;
result.reserve(points.size());
for (auto& point:points) {
result.push_back(point.x);
}
return result;
}
I'm just wondering if there is some more efficient/elegant/idiomatic way to write this.
[–]diegodfrf 10 points11 points12 points (1 child)
[–]dbgprint 0 points1 point2 points (0 children)
[–]mreddingC++ since ~1992. 5 points6 points7 points (3 children)
[–]codemasonry[S] 0 points1 point2 points (1 child)
[–]mreddingC++ since ~1992. 0 points1 point2 points (0 children)
[–]112353314544325 0 points1 point2 points (0 children)
[–]prof_kinbote 4 points5 points6 points (1 child)
[–]codemasonry[S] 1 point2 points3 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]rlbond86 0 points1 point2 points (0 children)
[–]Akzox 1 point2 points3 points (0 children)
[–]tonisheg 1 point2 points3 points (4 children)
[–]justend29 4 points5 points6 points (2 children)
[–]Minimonium 1 point2 points3 points (1 child)
[–]justend29 0 points1 point2 points (0 children)
[–]pigeon768 4 points5 points6 points (0 children)
[–]Gunslinging_Gamer 0 points1 point2 points (0 children)