Re: function to initialize vector from {1,2,3,4}
On 17.05.2012 16:55, franceschini.roberto@gmail.com wrote:
Hello,
copying from the web I maged to initialize a vector of integers from an array.
int myints[] = { 16, 2, 77, 29 };
vector<int> fifth(ord1, ord1 + sizeof(ord1) / sizeof(int));
Now I would like to turn this into a function that I can later call as
vector<int> myvec;
myvec = initialize_Vector( {1,2,3,4} )
I am becoming crazy with the passage of the array as argument of the function (pointer, values, ... dunno)
Can anybody explain how to write this function?
Of course any alternative solution that allows me to initialize
a vector by just specifying the values it contains in a one line
it's more than welcome
First, please dont't post lines that are longer than than about 77
characters. Such long lines may *look* like paragraphs, that are wrapped
nicely in some situations, but especially when quoted they tend to
appear as single, overly long lines. There is a format called "flowed"
that lets you post long paragraphs without manual line breaks. With that
format a space at the end of a line denotes a soft line break that can
be rearranged when the paragraph is formatted by client software. Please
use format "flowed" for those long paragraphs.
Anyway,
<code>
#include <iostream> // std::wcout, std::endl
#include <vector> // std::vector
template< class TpElem >
class Vector
: public std::vector< TpElem >
{
public:
typedef TpElem Elem;
typedef std::vector<Elem> Base;
int count() const { return Base::size(); }
Vector(): Base() {}
template< int n >
Vector( Elem const (&values)[n] )
: Base( values, values + n )
{}
};
int main()
{
using std::wcout;
using std::endl;
int const values[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
Vector<int> const v = values;
for( int i = 0; i < v.count(); ++i )
{
wcout << v[i] << " ";
}
wcout << endl;
}
</code>
Cheers & hth.,
- Alf