Produce a List of Integers Without Loops or Recursion

Without using any loops or recursion, how would I write a function getLengths that, given a vector of std::strings, uses std:: function templates to produce a list of integers containing the lengths of each string in the vector.
For example, if given a vector v0 with the strings ["abc", "", "defg", "h"], the call getLengths(v0) should return a list with the integers [3,0,4,1].

Using this declaration.

std::list<size_t> getLengths (const std::vector<std::string>& v0)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>
#include <iterator>

std::list<size_t> getLengths( const std::vector<std::string>& v0 )
{
    std::list<size_t> result ;
    std::transform( std::begin(v0), std::end(v0), std::back_inserter(result),
                    []( const auto& seq ) { return seq.size() ; } ) ;
    return result ;
}

int main()
{
    const std::vector<std::string> vec { "abcdef", "ghikl", "mnop", "qrs", "tu", "v", "" };
    for( std::size_t sz : getLengths(vec) ) std::cout << sz << ' ' ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/9aa71779297ede8e
Topic archived. No new replies allowed.