2

I want to make a template for an argument of a function.

The argument is a std::vector<type> with an allocator.

The default is to use the default memory allocator, but custom allocator can also be used.

The following code doesn't work. How to fix this?

template <typename T, typename T2=std::allocator<T>>
void pad_zero(std::vector<T,T2> vec, uint32_t n){
    uint32_t i;
    for (i = 0; i < n; i++){
        vec.push_back(0);
    }
}

Thanks.

10
  • coliru.stacked-crooked.com/a/3ad139c309b53f99 ; =std::allocator<T> isn't necessary. Commented Jul 20, 2016 at 19:53
  • 1
    Doesn't work how? Btw it'll change local variable vec only. Commented Jul 20, 2016 at 19:56
  • both intel c compiler and gcc complains using a <> within template <...>. The problem seems the second template argument depends on the 1st template argument. Commented Jul 20, 2016 at 19:59
  • 1
    >> is a problem in c++ standards before std c++11. It must be separated by space. Commented Jul 20, 2016 at 20:02
  • 1
    This seems like pretty much an imitation of std::fill_n, which you'd use like: fill_n(back_inserter(vec), n, 0); Commented Jul 20, 2016 at 20:08

2 Answers 2

4

You do not need to provide a default for the allocator. But really the problem is that you're padding a local variable - you accept vec by value!

Take it by reference, and drop the unnecessary default. Moreover, there's an overload of insert() that does exactly what you want, no manual looping necessary (which is not only verbose but inefficient due to the uncertain number of reallocations):

template <typename T, typename A>
void pad_zero(std::vector<T,A>& vec, uint32_t n) {
//                           ^^^
    vec.insert(vec.end(), n, T{0});
}
Sign up to request clarification or add additional context in comments.

Comments

2

You don't need to provide the allocator, template-argument-deduction will do that for you.

Note additionally that you're passing your vector by value, so inside pad_zero you get a copy of the vector, whilst the original one remains unchanged, which is probably not what you're looking for

See code below

http://coliru.stacked-crooked.com/a/5457167a4aeb36db

#include <iostream>
#include <vector>

template <typename T, typename A>
void pad_zero(std::vector<T,A>& vec, uint32_t n)
{
    uint32_t i;
    for (i = 0; i < n; i++)
    {
        vec.push_back(0);
    }
}

int main()
{
    std::vector<int> a = { 1, 2, 3 };
    pad_zero(a, 10);

    for (int i : a)
        std::cout << i << '\n';
}

Output:

1
2
3
0
0
0
0
0
0
0
0
0
0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.