what ctor for vector(size_type) items?

Hi,

Using vc++ 2003, I have an unexpected behaviour:
the following statement uses the copy-ctor to create
the vector items while I expected it uses the default-ctor:

std::vector<Foo> vFoo(10);

Am I wrong?

Marco.

// Full test program

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

class Foo
{
   int m_iVal;
public:
   Foo();
   Foo(const Foo & copy);
   void Print();
};

Foo::Foo()
{
   static int i = 0;
   ++i;
   m_iVal = i;
}

Foo::Foo(const Foo & copy)
{
   static int i = 100;
   ++i;
   m_iVal = i;
}

void Foo::Print()
{
   std::cout << m_iVal << std::endl;
}

int main()
{
   std::vector<Foo> vI(10);
   std::for_each(vI.begin(), vI.end(), std::mem_fun_ref(&Foo::Print));

   return 0;
}

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
marcosegurini
7/21/2003 8:44:50 PM
comp.lang.c++.moderated 10708 articles. 0 followers. allnor (8507) is leader. Post Follow

3 Replies
191 Views

Similar Articles

[PageSpeed] 44
"marco_segurini" <marcosegurini@virgilio.it> wrote in message news:a33fe984.0307202248.1eee8ef1@posting.google.com...
> Hi,
>
> Using vc++ 2003, I have an unexpected behaviour:
> the following statement uses the copy-ctor to create
> the vector items while I expected it uses the default-ctor:
>
> std::vector<Foo> vFoo(10);
>
> Am I wrong?

Yes.   The ten elements are filled by copying the second initializer argument.
The constructor you are using is essentially:
    vector(size_type n, const T& value = T())

The second arg in your case is defaulted to a default constructed Foo that is copied
ten times.



      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Ron
7/22/2003 12:43:41 AM
marco_segurini wrote:

 > Using vc++ 2003, I have an unexpected behaviour:
 > the following statement uses the copy-ctor to create
 > the vector items while I expected it uses the default-ctor:
 >
 > std::vector<Foo> vFoo(10);

The signature of this constructor is actually

  template < class T, class Alloc = std::allocator<T> >
  vector<T, Alloc>::vector( size_type n, const T& val = T(),
                            const Alloc& a = Alloc() );

So it default constructs one Foo (using the second
parameter's default argument) and copies it ten times.

--
Richard Smith

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Richard
7/23/2003 11:25:41 AM
"Ron Natalie" <ron@sensor.com> wrote in message news:3f1c531d$0$39702

> The constructor you are using is essentially:
>     vector(size_type n, const T& value = T())
>
> The second arg in your case is defaulted to a default constructed Foo that
is copied
> ten times.

Good point.  Class vector can be used to store objects with no default
constructor.

struct Foo {
   explicit Foo(int);
};

int main() {
   vector<Foo> v(10, Foo(10));
   v.push_back(Foo(11));
}

--
+++++++++++
Siemel Naran


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]
0
Siemel
7/23/2003 11:14:05 PM
Reply:
Similar Artilces:

What does Ctor::Ctor prototype mean?
Hi, For a class ABC. Can we declare the Ctor as ABC::ABC()? In particular for a class template, what is the semantics? Please look at the code below. It doesn't compile on VC2008. class Base { public: Base::Base() {} virtual ~Base() {} } ; template <class T> class ABC : public Base { public: ABC::ABC() {} // Line 16 error ~ABC() {} }; int main() { ABC<int> sp; } The errors are - main.cpp(16) : error C3254: 'ABC<T>' : class contains explicit override '{ctor}' but does not derive from an interface that contain...

Help on replacing an element in a vector (simulink)
Hi, I would like to replace a single element in a row vector data via an external input port to specify the index itself! How do I do this in Simulink? Thanks. ...

Need help for vectorize for-loop
Hi, Does any know some trick to vectorize following for-loop? for j=1:n_h for i = 1:m_h output(t(i,j),j) = h(i,j) + output(t(i,j),j); end end In article <1171754098.630505.263660@k78g2000cwa.googlegroups.com>, "mailcwc@gmail.com" <mailcwc@gmail.com> wrote: > Hi, > > Does any know some trick to vectorize following for-loop? > > for j=1:n_h > for i = 1:m_h > output(t(i,j),j) = h(i,j) + output(t(i,j),j); > end > end ------------------ [j,i] = meshgrid(1:n_h,1:m_h); output = full(sparse(t,j,h,m_h,n_h)); Roger ...

Vector * Matrix
Hi could any one help iv created a formula in excel which iv tried to re-create in Matlab but it is coming out with a different value. CovMatrix = 10x10 Matrix PosVal = 10x1 Vector My forumla in excel is: VP = MMULT(CovMatrix, PosVal) PortVar = MMULT(transpose(PosVal), VP) My forumla in Matlab is: VP = CovMatrix * PosVal PortVar = PosVal' * VP VP on both occasions comes out the same put then when i multiply this by the transpose of the PosVal this is where it seems to come out different. Thanks "James " <james.pearson@schneidertrading.com> wrote i...

Program to delete SD card items?
Hi all I am looking for a prog to delete files in my SD card... Filez doesn seem to allow me to do that.... any other software (free hor!) can d it -- Pet ----------------------------------------------------------------------- Pete's Profile: http://www.micromagiclabs.com/forums/member.php?userid=8 View this thread: http://www.micromagiclabs.com/forums/showthread.php?t=2395 Pete wrote: > Hi all, > > I am looking for a prog to delete files in my SD card... Filez doesnt > seem to allow me to do that.... any other software (free hor!) can do > it? >...

Vectors are not shown in splot
Hi all, I want to plot a 3D sample of points (namely stars) where the positions are shown as points (obviously) and the distances to a reference point or plane are shown as vectors (namely as animated GIF, therefore the GIF terminal). I have tried something like the simplified example below. As one can see, the color of the vectors is black although defined as blue. I guess that there is some conflict between the data-dependent rgb coloring and the linecolor (lc) setting or in general between the colors of points and vectors. Or did I make some stupid mistake here? set ...

copy ctor being private and compilation error
Consider the following program x.cpp: #include <cstdlib> #include <iostream> using namespace std; class Test { public: explicit Test(int arg = 10); ostream& writeTo(ostream& os) const; private: Test(const Test& rhs); int val; }; inline Test::Test(int arg) : val(arg) { cout << "Test one-argument-ctor called" << endl; } inline ostream& Test::writeTo(ostream& os) const { return os << val; } inline ostream& operator<<(ostream& os, const Test&...

In a loop FOR, how to rename sequentially a sequence of vectors of different sizes ?
Hi, Considering a generic matrix a(5,5), in the loop : for t = 1:5 x= zeros(sum(a(:,t)),1) end How can I rename x for every t ? I mean: for t=1, x1; for t=2, x2; for t=3, x3 ... Does anybody have an idea ? Thanks! Renato Armelin: <SNIP wants to dynamically name his/her variables in a loop> > How can I rename x for every t ? > Does anybody have an idea ? yes, we do, BUT: we don't like this approach. can you tell CSSM why you would not rather use <cell>s for your task? this would most certainly be advantageous! sorry for being malicious us ...

Merge vectors
Hi everyone, I need help once again and I hope you can help me as I haven't found a real solution. I have to vectors: a = [1,2,3] and b=[4,5,6] and now I need a command to merge them into this: command(a,b)=[1,2,3,4,5,6] I hope you got something :D On Oct 8, 10:05=A0am, "adam " <unique...@gmail.com> wrote: > Hi everyone, > > I need help once again and I hope you can help me as I haven't found a re= al solution. > > I have to vectors: > a =3D [1,2,3] and b=3D[4,5,6] > > and now I need a command to merge them into this: > command(a,b)=3D[1...

How to differentiate the first or last item in Java 5 for-each type of loop?
Hello there! I got a code snippet like: // == start of the code == List<String> list = new ArrayList<String>(); ....// some code to add String to "list" for (String item : list) // Java 5 for-each loop { // do something. .. // but also want to something special for the first/last item of the loop. } // == end of the code == So my question is: how can I catch the first/last item, without roll the code back to the old iterator-style of loop. Thanks a lot for any comments! Chris whmanutd@gmail.com wrote: > Hello there! > > I got a code snippet like: ...

reference to pointer used in ctor - using 'this' in ctor (repost
template<class T> class A { public: A() { T * object = new T(this); //passing instance as parent of nested class m_obj.push_back(object); } ~A() { for (std::vector<T>::iterator it= m_obj.begin(); it != m_obj.end(); it++) delete *it ; } private: std::vector<T*> m_objs ; }; class B { public: friend class A; ~B(){}; private: B(A<B>* parent):m_parent(parent){} A<B>* m_parent ; }; class C { public: friend class A; ~C(){}; private: C(A<C>*& parent):m_parent(parent){} A<C&...

about static vector (of pointers) member function
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token vector_static_function.c:21: error: expected constructor, destructor, or type conversion before '.' token when compiling this: // about static vector (of pointers) member function #include <iostream> #include <vector> using namespace std; class G4PreCompoundModel { public: static vector<int*> * GetCreatorModels() { return &G4PreCompoundModel::theCreatorModels; ...

Move semantics and ctor
When should one consider implementing a an explicit move ctor (such as Class::Class(const Class&&) ) ? Thank you in advance ! AP wrote: > When should one consider implementing a an explicit move ctor (such > as Class::Class(const Class&&) ) ? Thank you in advance ! Without the const... When the const of copying the class makes a move constructor worth while. -- Ian Collins On Sat, 20 Sep 2014 19:50:45 -0700 (PDT) AP <udtelco@gmail.com> wrote: > When should one consider implementing a an explicit move ctor (such > as Class::Class(const Clas...

REQ: Heraldry Clipart
REQ: Heraldry Clipart - any format, but I Prefer Vector. THANKS --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading made easy =--------- -= Get GrabIt for free from http://www.shemes.com/ =- + hmmm... doing a quick websearch, using "heraldry clipart" I found this free site... http://www.heraldicclipart.com/ This type of art is easily traced... vectorized... and colored RamRod wrote: > REQ: Heraldry Clipart - any format, but I Prefer Vector. THANKS > > > --------------= Posted using GrabIt =-------...

Small D6 Bug: No start menu item created for unlocked image
After installing D6 and rebooting, I started the "Fresh Install" icon of D6. I entered my license key and specified the target directory in the default location. D6 then created the image file there and I saved and exited the image. However D6 did not create a start menu icon for the new image (like D5 did). No big problem, since I was able to create one myself, but it should be fixed (assuming that the problem is reproducible). Best Regards, Bernhard Bernhard, > After installing D6 and rebooting, I started the "Fresh Install" icon > of D6. I en...

plotting vectors into step functions
Hello, I want to create heaviside functions that go randomly either 1 to -1 with the square wave having a period of 2 seconds. I have already generated the random numbers into a vector such as [1 -1 1 1 -1] etc. So how do I plot this vector now into a step function? I want to do it in heaviside functions.. I can get the plot of the vector but can't get step functions it just connects the points. Also it starts at 1 and not 0 and I need it to start at 0. If someone could help me that would be great.. I also will need to end up integrating this wave into triangle wave at the right times b...

Why does the menu items take so much space?
Hi, Can somebody tell me why the menu on the url below needs so much space between menu items? (between the home, browses, forms, pages). Maybe a margin / padding problem, but I cannot seem to find it. The URL: http://www.genwise.com/temp/ordersbrowse.aspx.htm Thank you! -- Ward Bekker Fri, 24 Mar 2006 16:36:01 +0100 from Ward Bekker <ward@NospaaMequanimity.nl>: > Can somebody tell me why the menu on the url below needs so much space > between menu items? (between the home, browses, forms, pages). > > Maybe a margin / padding problem, but I cannot...

Vectors
Hi All, I'm a math senior high school teacher, and I wish to understand how using mathematica 7 to find "h" and the intersection point between the plane 6x-2y+z=11 which contains the line x-1 = (y+1)/2 = (z-3)/h. Also how to plot/show it visually in 3D graph. Many thank's. Harry. On 1/14/2012 2:01 AM, Harry Har wrote: > Hi All, > > I'm a math senior high school teacher, and I wish to understand how > using mathematica 7 to find "h" and the intersection point between the > plane 6x-2y+z=11 which contains the line x-1 = (y+1)/2 ...

vectorization: lengths of vectors in a cell
Dear all, I have a cell comprising many vectors: C= [1 x n1 uint32] [1 x n2 uint32] [1 x n3 uint32] ... [1 x nk uint32]; I need to extract lengths of all these vectors: L = [n1, n2, ... nk]; I can use a loop to find L, but is there a cleaner/simpler way? Thanks. "Akim " <aaa@bbb.ccc> wrote in message <hgms1o$si5$1@fred.mathworks.com>... > Dear all, > > I have a cell comprising many vectors: > > C= > [1 x n1 uint32] > [1 x n2 uint32] > [1 x n3 uint32] > ... > [1 x nk u...

item groups and display order
hello, I have two images grouped and I would to change the display order to display the one behind in foreground. I tried : $canvas->creategroup([0,0],-members=3D>[$id_imagebehind, $id_imagefront]); $canvas->raise($id_imagebehind,$id_imagefront); but it does'nt work. The image that is always displayed is the last in members list. any idea to resolve this pr ?? Is there a method to hide an image in canvas, and so in a group ???? Thanks Herv=E9 On 15 May 2007 06:02:28 -0700, RV <rvlebars@hotmail.com> wrote: >hello, > >I have two image...

Gravity Vector Tracking
Looking for suggestions or pointers on how to track the gravity vector in 6D data. -- Randy Yates Digital Signal Labs http://www.digitalsignallabs.com On 5/1/2013 2:54 PM, Randy Yates wrote: > Looking for suggestions or pointers on how to track the gravity vector > in 6D data. > http://en.wikipedia.org/wiki/Equivalence_principle VLV Vladimir Vassilevsky <nospam@nowhere.com> writes: > On 5/1/2013 2:54 PM, Randy Yates wrote: >> Looking for suggestions or pointers on how to track the gravity vector >> in 6D data. >> > > http:/...

conditions for automatic generation of default ctor, copy ctor, and default assignment operator (operator)
From my understanding, if you declare any sort of constructors, (excluding copy ctor), the default will not be included by default. Is this correct? class Foo{ public: Foo(int); // no Foo() is included, i believe. }; Under which conditions a default copy ctor and default assignment operator are not included? Thanks. "puzzlecracker" <ironsel2000@gmail.com> wrote in message > From my understanding, if you declare any sort of constructors, > (excluding copy ctor), the default will not be included by default. Is > this correct? No, even declaring/defi...

How to np.vectorize __call__ method
I am cross-posting from: http://stackoverflow.com/q/19990863/886669 I am following, [quant-econ](http://quant-econ.net/numpy.html) tutorial. I am trying the exercise where I am supposed to implement a [Empirical Cumulative Probability Funcion](http://en.wikipedia.org/wiki/Empirical_distribution_function) using vectorized numpy methods. Here is the **correct** solution to problem: class ecdf: def __init__(self, observations): self.observations = np.asarray(observations) def __call__(self, x): return np.mean(self.observations <=...

copy ctor vs default ctor
If we do not provide any ctor for a class, the compiler provides the default ctor and copy ctor if needed. Consider a class Test. Suppose we provide some ctor in class Test but do not provide the default ctor. Suppose we try to create Test obj; Here the default ctor is needed and the compiler does not provide the default ctor but generates a compilation error. However if we provide some ctor but do not provide the copy ctor, the compiler does not generate error but provides the copy ctor if needed. Why doesn't the compiler give error for the absence of copy ctor similar to error for ...

vector quantization #4
sir/madam, I am doing my project in image compression using vector quantization. I want to implement lloyd algorithm and can any one help me with code? Thanks with regards, Nagendran ...