저는 C ++를 배우고 있으며 다음 코드를 개선 할 수있는 방법을 알고 싶습니다.
std::vector<float> distances;
std::for_each(play_->get_emps().begin(), play_->get_emps().end(), [distances, tank] (const auto& e) {
distances.push_back(math::distance(e.location(), tank->location()));
});
벡터를 std :: algorithms로 채우는 더 좋은 방법이 있어야합니다.
std::transform
범위 (또는 두 범위)의 각 요소에 함수를 적용하고 결과를 다른 범위에 저장하는 알고리즘입니다 (모든 입력 범위와 동일 할 수 있음).
std::vector<float> distances;
std::transform(play_->get_emps().begin(), play_->get_emps().end(),
std::back_inserter(distances),
[tank](const auto& e) {return math::distance(e.location(), tank->location();});
<algorithm>
모두 멋지지만 때로는 과잉 IMO입니다. for
루프는 더 간단합니다.
std::vector<float> distances;
for(const auto& e: play_) {
distances.push_back(math::distance(e.location(), tank->location()));
}
Marc Glisse 가 의견에서 언급했듯이 두 버전 모두 std::vector::reserve
미리 호출하면 도움이 될 것 입니다. push_back
자주 매우 비효율적 사용하는 경우 ( std::back_inserter
사용 push_back
내부적으로뿐만 아니라)
std::vector<float> distances;
distances.reserve(play_.size());
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다