initializing the array

Discussion in 'C++' started by anon, Aug 12, 2008.

  1. anon

    anon Guest

    Hello,

    Considering the following code:


    /// code
    #include <vector>
    #include <iostream>

    template< int N >
    class a
    {
    public:
    a( const float p[] ) :
    v( &p[0], &p[0] + N )
    {
    }

    void print()
    {
    std::cout<<"Stored array = ";
    for (int i = 0; i < N; ++ i )
    {
    std::cout<<v.at(i)<<" ";
    }
    std::cout<<std::endl;
    }

    std::vector< float > v;
    };

    int main()
    {
    a< 2 > obj( (float[]){ 0.3, 0.5 } );
    obj.print();
    }
    /// end of code


    when I compile using gcc with -pedantic-errors option, I get next error:
    error: ISO C++ forbids compound-literals
    comeau online agrees there is a problem there.

    But gcc without -pedantic-errors compiles and executes fine.

    Am I causing an undefined behavior somehow?
    Is there a way to do what I want, without getting that error? I need to
    enable -pendantic_errors

    Thank you in advance
    anon, Aug 12, 2008
    #1
    1. Advertising

  2. anon

    anon Guest

    This program is doing almost what I want (take a look into the
    declaration of the obj object). I took the idea from boost list_of :

    #include <vector>
    #include <iostream>
    #include <cassert>

    template< int N >
    class a
    {
    public:
    explicit a( const float p ) :
    v( N, p ),
    i(0)
    {
    }

    a& operator() ( const float p )
    {
    this->v.at(++i) = p;
    return *this;
    }

    void print() const
    {
    assert( (N-1) == i );
    std::cout<<"Stored array = ";
    for (int i = 0; i < N; ++ i )
    {
    std::cout<<v.at(i)<<" ";
    }
    std::cout<<std::endl;
    }

    std::vector< float > v;
    int i;
    };

    int main()
    {
    const a< 2 > obj( a< 2 >( 0.3 )( 0.5 ) );
    obj.print();
    }
    anon, Aug 12, 2008
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. newby1

    initializing an array

    newby1, Jul 3, 2004, in forum: Java
    Replies:
    3
    Views:
    444
    Hal Rosser
    Jul 4, 2004
  2. Replies:
    11
    Views:
    1,097
  3. J. Campbell
    Replies:
    4
    Views:
    8,404
    Gianni Mariani
    Jan 29, 2004
  4. Steven T. Hatton
    Replies:
    1
    Views:
    6,616
    Siemel Naran
    Apr 19, 2004
  5. Pedro Miguel Carvalho

    Problem initializing class with literal array!

    Pedro Miguel Carvalho, Oct 21, 2004, in forum: C++
    Replies:
    3
    Views:
    7,929
    Victor Bazarov
    Oct 21, 2004
Loading...

Share This Page