Is it possible to create an Std::list with an initializer_list?

Asked

Viewed 73 times

1

I’d like to pass one std::list temporary to a function, but do not know if it is possible to do it. I know it is possible to pass a std::vector temporary with a initializer_list:

#include <iostream>
#include <vector>

template<typename T>
void mostra(const std::vector<T>& myVec)
{
    for(T var : myVec)
        std::cout << var << "\n";
}

int main()
{
    mostra<int>({12, 14, 28, 7, 10});
    return 0;
}

1 answer

0


Works for me:

#include <iostream>
#include <list>

template<typename T>
void mostra(const std::list<T>& myList)
{
    for(T var : myList)
        std::cout << var << "\n";
}

int main()
{
    mostra<int>({12, 14, 28, 7, 10});
    return 0;
}
  • Always good to give a test :)

  • Exactly, when the function ends the lists go out of scope. And no need to apologize XD

  • No, for that already has the stackoverflow.com normal.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.