Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > initializing the array

Reply
Thread Tools

initializing the array

 
 
anon
Guest
Posts: n/a
 
      08-12-2008
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
 
Reply With Quote
 
 
 
 
anon
Guest
Posts: n/a
 
      08-12-2008

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();
}
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Why no compiler-warning at invalid array-initializing ? carlos@gkpwdun.com Java 11 11-07-2005 08:34 PM
Problem initializing class with literal array! Pedro Miguel Carvalho C++ 3 10-21-2004 04:12 PM
initializing an array newby1 Java 3 07-04-2004 04:05 AM
Initializing a static const member array of a class type Steven T. Hatton C++ 1 04-19-2004 06:42 AM
initializing a const array in a class J. Campbell C++ 4 01-29-2004 03:45 AM



Advertisments