Home > Enterprise >  does C have spread operator?
does C have spread operator?

Time:11-05

can you do this in C :

vector<int> v1={1,2}, v2={3,4};
vector<int> v3={...v1, ...v2, 5};
//v3 = {1,2,3,4,5}

What is the simplest way to do this with C ?

CodePudding user response:

I would implement it with a helper function like this. Online demo here : https://onlinegdb.com/AnA3GkbQL This template code kind of writes out all the individual push_backs and inserts needed to get the final result (at compile time).

#include <iostream>
#include <vector>

namespace details
{
    template<typename type_t, typename arg_t, typename... args_t>
    auto make_spread_impl(std::vector<type_t>& values, const arg_t& arg, const args_t&... args)
    {
        // check if template argument is a value or a std::vector of values.
        if constexpr (std::is_same_v<arg_t, type_t>)
        {
            // single value
            values.push_back(arg);
        }
        else
        {
            // vector of values
            static_assert(std::is_same_v<std::vector<type_t>, arg_t>);

            // append values to end
            values.insert(values.end(), arg.begin(), arg.end());
        }

        // continue recursion
        if constexpr (sizeof...(args_t) > 0)
        {
            return make_spread_impl(values, args...);
        }

        // recursion end condition
        return values;
    }
}

template<typename type_t, typename... args_t>
auto make_spread(const args_t&... args)
{

    // one argument return a vector of values.
    if constexpr (sizeof...(args) == 1ul)
    {
        return std::vector<type_t>{args...};
    }
    
    // otherwise recurse
    std::vector<type_t> values;
    details::make_spread_impl(values, args...);
    return values;
}



int main()
{
    std::vector<int> v1{ 1,2,3 };
    std::vector<int> v2{ 5,6,7 };

    auto result = make_spread<int>(v1, 4, v2, 8);

    for (const auto& value : result)
    {
        std::cout << value << " ";
    }


    return 0;
}

CodePudding user response:

No spread operator in C .

Probably the simplest way would be a sequence of inserts

std::vector<int> v3;
v3.insert(v3.end(), v1.begin(), v1.end());
v3.insert(v3.end(), v2.begin(), v2.end());
v3.insert(v3.end(), 5);

Various range libraries have a concat function

auto v3 = ranges::views::concat(v1, v2, { 5 }) | 
          ranges::views::join | 
          ranges::views::to<vector>; 

C 23 or ranges::v3. Still more verbose than spread operator.

  • Related