Namaran

Code daily. Without assist.

2026-09-03

word_lengths.cpp

#include <print>
#include <string>
#include <vector>

std::vector<std::size_t> lengths(const std::vector<std::string>& words) {
    std::vector<std::size_t> out;
    out.resize(words.size());
    for (const auto& w : words)
        out.push_back(w.size());
    return out;
}

int main() {
    for (std::size_t n : lengths({"tea", "milk", "sugar"}))
        std::print("{} ", n);
    std::println();
}

lengths は、単語の長さを同じ順に並べた vector を返すつもりの関数です。引数も標準入力も使わず、main が {"tea", "milk", "sugar"} を渡して結果を1行に出力します。いまは 0 0 0 3 4 5 と出力されますが、本来は 3 4 5 です。

Answer

Wrong

std::vector<std::size_t> out;
out.resize(words.size());
for (const auto& w : words)
    out.push_back(w.size());

resize(words.size()) は、単語と同じ3個の要素を 0 で作ります。push_back は最後の要素の後ろ、つまりこの3個の後ろに足すので、長さは4番目から並び、先頭には 0 が3つ残ります。

Right

std::vector<std::size_t> out;
out.reserve(words.size());
for (const auto& w : words)
    out.push_back(w.size());

reserve は3個分の容量を先に確保するだけで、要素数は 0 のままです。最初の push_back が先頭に入り、ループの途中で再確保も起きません。resize を残すなら、push_back をやめて添字で代入する形にそろえます1。

  1. reserve の行を消しても結果は同じです。変わるのは、ループの途中で起きる再確保の回数だけです。