How to calculate the average length of the strings in a vector of strings with C++

1 Answer

0 votes
#include <iostream>
#include <numeric>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> arr = {"c#", "c", "java", "python", "c++"};

    int totalLength = std::accumulate(arr.begin(), arr.end(), 0, [](int sum, const std::string& s) {
        return sum + s.length();
    });

    double avg = static_cast<double>(totalLength) / arr.size();

    std::cout << avg << std::endl;
}

 
/*
run:
 
3.2
 
*/

 

 



answered Aug 20, 2024 by avibootz
...