what ctor for vector(size_type) items?

  • Permalink
  • submit to reddit
  • Email
  • Follow


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
Reply marcosegurini 7/21/2003 8:44:50 PM

See related articles to this posting


"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
Reply 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
Reply 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
Reply Siemel 7/23/2003 11:14:05 PM
comp.lang.c++.moderated 10662 articles. 10 followers. Post

3 Replies
161 Views

Similar Articles

[PageSpeed] 7


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

vector of vector of vectors
Hi, I'm having a problem that's driving me nuts right now. I wanted to represent data as a vector<vector<vector<unsigned short> > > Now I've been having alot of trouble initializing and accessing elements for that type. I can't seem to initialize like blah(10,10,10) to make each vector length 10, so instead I did blah(10,(10,10)) but even though that compiles I get runtime errors if I ever do something likeblah.at(i).at(j).at(k), no matter what the values of i j and k. Is there a clean way to do what I want it to do or should I just not try it this wa...

Remove an item from a vector and write to file the contents of the Vector
Hi all, I am currently developing a java application that has to deal with it reading ina CSV file and populating the data that is inside the CSV file into a vector and then places what is inside the Vector into a JList. When the user selects an item from the JList and then they press the delete button the item that they selected would get removed from the JList. Once the item has been removed from the JList I then want the application to write the information that is left inside the vector to a file without it having any commas or square brackets etc. I am fairly new to Java and therefore ...

issues with vector of vector of vectors
Gurus, Is this possible to do? Do any of you see any issues? typedef pair<string, string> myPair; typedef vector<myPair> myPairVector; typedef vector<myPairVector> myPairVectorColl; typedef vector<myPairVectorColl> myPairVectorCollCollection; Now when I initialize a variable of myPairVectorCollCollection, the size of this vector is unusually large( both in the debug as well as release versions ) And when I look at the stack trace during debugging, I am going nuts...this is how it shows up( even though the vector has only two elemts): _Mylast = [3291966109]([...](),[...

Vector of vector or matrix of vector
Hi all; I want to have a vector which each component of vector. For example I want to have vector of n random matrix of dimension m. How to get this?? Thanks Hypermatrices (help hypermatrices) should be the answer. Eric. On Apr 18, 8:44 pm, high-sco...@caramail.com wrote: > Hi all; > I want to have a vector which each component of vector. > For example I want to have vector of n random matrix of dimension m. > > How to get this?? > > Thanks ...

A Vector of Vectors
Hi, This problem could just as easily generalize to a vector of matrices. Here it is, I am having a bit of difficulty constructing a vector of vectors of varying lengths. That is, T1 is a mx1 vector T2 is a nx1 vector .. .. .. TX is a zx1 vector where X,m,n,z are all positive integers. Ideally, if these were all the same length, I would just construct T = [T1 T2 ... TX] such that I could access Tj with T(:,j). But if these vectors are different lengths, how would I efficiently put them into one vector or cell such that I could index each vector easily? I realize I could zero pad each one ap...

vector of vectors
I wanted to make a vector of vectors of int so I tried following : #include<iostream> #include<vector> int main() { vector<vector<int> >vec; for(int i=0;i<2;i++) { vector<int>newVec; vec.push_back(newVec); for(int j=0;j<3;j++) { std::cin>>num; vec[i].push_back(num); // Here vec[i] works but newVec.push_back (num) doesn't work. Why? } } } happy wrote: > I wanted to make a vector of vectors of int so I tried following : > > #include<iostream> > #include<vector&g...

Vectors in a vector
Hi all, How can i have a vector like: v=[1, 3, [1, 5]]? it cann't work to have this vector by u=[1, 5] and v=[1, 3], and v(1, 3)=u. It'll appear the error message: ??? Subscripted assignment dimension mismatch. Can anyone help me with that? Thanks a lot. Samuel@Taiwan On Wed, 20 Sep 2006 18:39:13 -0700, samuel wrote: > Hi all, > > How can i have a vector like: v=[1, 3, [1, 5]]? it cann't work to have > this vector by u=[1, 5] and v=[1, 3], and v(1, 3)=u. It'll appear the > error message: > > ??? Subscripted assignment dimension mismatch....

vector::size_type
Is std::vector<T>::size_type guaranteed to be the same type as std::vector<U>::size_type? To be more explicit, given void f(T, U); and std::vector<T> vt; std::vector<U> vu; which have the same size, can I write for (std::vector<T>::size_type i = 0; i < vt.size(); ++i) f(vt[i], vu[i]); or should I write for (std::vector<T>::size_type i = 0; i < vt.size(); ++i) f(vt[i], vu[static_cast<std::vector<U>::size_type>(i)]); Thank you. On 2007-10-09 23:18, t.hall@liv.ac.uk wrote: > Is std::vector<T>::size_type guaranteed to be t...

Vector of Vectors.
I'm having a bit of trouble manipulating an element of a vector of vectors. I'm using GNAT GPL 2008. Here is a small program to illustrate the issue: with Ada.Containers.Vectors; procedure Check is package Integer_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer); package Nested_Vectors is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Integer_Vectors.Vector, "=" => Integer_Vectors."="); IV : Integer_Vectors.Ve...

Free memory allocate by a STL vector, vector of vector, map of vector
Hi, I have the following code which frees memory allocate by a STL vector, vector of vector, map of vector. I would like to know if I indeed free all the memory (i.e. no memory leak). Thanks for any advice: /* From Effective STl */ struct DeleteObject { template<typename T> void operator()(const T* ptr) const { delete ptr; } }; typedef vector<A*> AVector; // free a vector of 'A*' void f4(AVector& aVector) { for_each(aVector.begin(), aVector.end(), DeleteObject()); aVector.clear(); } // free a vector of vector of 'A*' void f4(vector<AVector*&...

explicit ctor in vector
In the standard library vector, the ctor explicit vector::vector(size_type __n) is declared as explicit. I am unable to get the reason for it being declared as explicit. Kindly clarify with an example. Does the standard require that this ctor should be declared explicit ? Also, please let me know if there are any guidelines for identifying which 'one argument ctors' need to be declared as explicit. Thanks V.Subramanian subramanian100in@yahoo.com, India wrote: > In the standard library vector, the ctor > explicit vector::vector(size_type __n) > > is declared as explici...

Matching Items in a vector
Hi - I was using two arrays to go through two lists of numbers in the same format, such as below: The numbers are always 15 numbers followed by some text. I ONLY care about the first 15 numbers, not the text. 100121242110124ABC 000121241000124ABC 000121236300124ABC 000121236300124ABC 005151533414124ABC 001121231009909ABC 000124576700188ABC 123516800785656ABC I had passed both sets of numbers into two separate arrays, and was able to use the regionMatches method to compare the first 15 numbers to find duplicates. I want to be able to remove any duplicates from t...

how to ensure that a vector is a column vector or row vector?
I don't have to ask this if the Matlab is smart enough; but it isn't. for example, x./y if x is a row vector and y is column vector, or vice versa, the Matlab will report error... So I want to know a way to ensure that a vector is column vector or a row vector... Thansk If you just want everything to be the same (row or column) a = rand(100,1); b = rand(1,100); a = a(:); b = b(:); Mike wrote: > > > I don't have to ask this if the Matlab is smart enough; but it > isn't. > > for example, > > x./y > > if x is a row vector and y is column ...

Shutdown Items -- Startup Items -- Wakeup Items ???
Do Wakeup Items (wake up from Sleep) exist? Could they? ...

Coarray
Hi, I am going to write a coarray implementation of a sparse iterative solver. Are there any comparisons/notes on different array/vector or vector/vector multiplications implementations? I read that, for vector/vector a binary tree reduction sum in coarray is a good choice. But what about array/vector implementations? Thank you Jan On Thursday, November 20, 2014 11:20:44 AM UTC+1, Jan Wittke wrote: > I read that, for vector/vector a binary tree reduction sum in > coarray is a good choice. > But what about array/vector implementations? Just a side remark: The upc...

vector within a vector
It's late. Why is the compiler saying that this is the wrong syntax: vector<vector<cIndicatorValue>> ranks; One other question: If I want to access one of cIndicatorValue's functions, I have to declare a vector iter, right? Can I add an integer to an a vector iter to move it through the array? Angela wrote: > It's late. Why is the compiler saying that this is the wrong syntax: > > vector<vector<cIndicatorValue>> ranks; Because the '>>' immediately after the cIndicatorValue is being interpretted as an operator. Try using whites...

Vector index into vector
In general, if A is an array, and V is a vector used to index into A (via linear indexing), then the shape of A(V) is equal to the shape of V itself. However, if A is a row vector, then A(V) will be a row vector regardless of whether V is a row or column vector. Similarly, if A is a column vector, then A(V) will be a column vector. [I hope that made sense!] Is there some rationale behind that seeming inconsistency? Is there any clever way to ensure that A(V) is always the shape of V? The best I can come up with is: >> reshape(A(V),size(V)) ...

vector of vectors #2
Hi, I've created a vector of vectors of ints, and I want to pass it as a parameter to a function. Is this possible, and if so, then what is the syntax like for the function header and function prototype when I need to specify the variable type? Thank you, N. "Nancy Keuss" <muse188@aol.com> wrote... > I've created a vector of vectors of ints, and I want to pass it as a > parameter to a function. Is this possible, and if so, then what is the > syntax like for the function header and function prototype when I need > to specify the variable type? By value: ...

Sizing a vector of vectors
Hello, I'm trying to size a vector of vectors of unsigned ints to be an NxN square. Here's how I'm doing it: typedef vector<vector<unsigned int> > tournament_type; unsigned int n; tournament_type tournament; // Go get a value for n... tournament.resize(n); for_each( tournament.begin(), tournament.end(), bind2nd(mem_fun1(&tournament_type::value_type::resize), n) ); On the platform I'm on (VC++ 7.1), I get an internal compiler error. Before I go over to the VC++ group, I'd like to make sure this code should...

Problem with deleting vector items
Hi. I got a problem with deleting items of a vector. I did it like this: void THIS::bashDelPerson() { cout << "Bitte Suchstring eingeben: "; char search[128]; cin >> search; vector<Person>::iterator iter; iter = persons.begin(); Person* person; while ( iter != persons.end() ) { if ( strstr(iter->getFirstName(), search) != 0 ) { persons.erase(iter); } cout << "Moep\n"; if(iter != persons.end()){iter++;} } } But this implementation only works if the Person, which should be deleted is the last one. If it is followed by another...

Directly Modify Vector Item
Is it possible to directly manipulate an item within a Vector (or anyother AbstractCollection).Basically, I retrieve and manipulate vectors in the following way:Vector myVec = new Vector();// populate...for (int i = 0; i < myVec.size; i++) { String myStr = (String)myVec.get(i); myStr = "String " + i; myVec.setElementAt(myStr, i);}While arrays can simply modify directly:for (int i = 0; i < myVec.size; i++) { myArray[i] = "String " + i;}The first method seems cumbersome and inefficient, especially whenusing a class other than a String (one with many modifications to...

Creating a vector out of other vectors
Hi, I have the following problem: library ieee; use ieee.std_logic_1164.all; entity test is port(ep_to_send : in std_logic_vector(3 downto 0); addr_to_send : in std_logic_vector(6 downto 0); data_valid_to_send : in std_logic; direction_to_send : in std_logic ); end test; architecture rtl of test is signal test_vector: std_logic_vector(9 downto 0); begin test_vector <= (addr_to_send(4 downto 0) & ep_to_send & data_valid_to_send); end rtl; Is this legal in VHDL? Will the new vector be composed correctly? Thank...

Vector of vector question
If I create a vector of vectors of double: std::vector< std::vector<double> > table1; Are my vectors of doubles uninitialized? Do I have to loop through table1 and initialize each vector of doubles using new? And in cleaning up, manually delete each of these vectors of doubles? Thanks, B "BCC" <bryan@akanta.com> wrote in message news:gvHMb.9111$wP1.6082@newssvr27.news.prodigy.com... > If I create a vector of vectors of double: > > std::vector< std::vector<double> > table1; > > Are my vectors of doubles uninitialized? No. They ar...

fitting vectors with other vectors
Hi I am stuck in trying to fit a spectrum (S) with two other spectra (A and B) which I already know to be combined in S. i.e. I want to use two vectors (A and B) to fit a third vector S, which is a linear combination of A and B. How can I say thus that S= a*A + b*B, and get the coefficients (a and b) of the linear combination? I guess the problem here is that I don't have an indipendent variable... Many thanks for your help DG "damiano Genovese" <damianogeno@libero.it> wrote in message <i9hj4o$gc0$1@fred.mathworks.com>... > Hi I am stuck in trying to fit a s...