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 10647 articles. 9 followers. Post

3 Replies
147 Views

Similar Articles

[PageSpeed] 42


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

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 ...

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...

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...

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...

std::vector ctor guarantee.
I'd like to know that when I use the InputIterator, InputIterator version of the vector ctor, or that particular insert overload, is it guaranteed that reserve will be called, and the copes will be made only once. Particularly, something like this: vector<int> v (23, 45); vector<int> v1 (v.begin(), v.end()); //Any guarantee that elements will be copied only once. ie: Only 23 copies will be made when this statament executes? Or do I have to manually call reserve before a call to insert which has a similar signature? Also one more thing. If I have a type such as int*, then do ...

How to compare items in a column vector?
Hello, Let's say I have a 6x4 matrix looking like: 1 6 56 45 2 4 7 18 3 91 56 4 2 6 56 45 1 91 56 4 3 4 7 18 The first column represents conditions 1, 2, and 3, where each condition is repeated twice. The numbers in the last 3 columns are random. What I wish to do is take the rows for each condition and determine the mean across the repetitions. How can I compare each item in the first cloumn vector to see if they equal and then take the mean across the rows that have an equal value in that first cell? Thanks, it will be greatly appreciated!...

Remove items from a stl vector
How can I remove items from a stl vector if it exists on another vector? In Java, I can do this: vector v1 = new Vector(); // populate v1 vector v2 = new Vector(); // populate v2 v1.removeAll(v2); how can I do that in C++? Do I have to write my own functor and pass that to remove_if() algorithm? silverburgh.meryl@gmail.com wrote: > How can I remove items from a stl vector if it exists on another > vector? Which one do you designate 'it'? The item or the vector? > In Java, I can do this: > vector v1 = new Vector(); > // populate v1 > > vector v2 = new Vect...

vector::emplace_back multiple items
{ text has been reformatted to ~70 chars per line. -mod } I came up with the following solution to work around the fact that vector::emplace_back allows the insertion of only one single element at a time. My requirements are the use of a move-only type (see struct A below), so the initializer_list version of the vector ctor is a no-go. Following is i) the definition of the A type, ii) the template functions implementing the logic, iii) a sample main function. #include <iterator> #include <iostream> #include <utility> #include <vector> using namespace s...

Wrong vector ctor used with iterator
I have this iterator: class CFileIterator : public std::iterator<std::input_iterator_tag, const std::wstring> { public: CFileIterator(const std::wstring& wildcardPath); .... }; which I instantiate like this: CFileIterator it(SomePathWithWildcard), end; I was hoping to be able to fill a vector using the iterator, like this: std::vector<std::wstring> filenames(it, end); but the compiler spits this into my face: error C2664: 'std::vector<_Ty>::vector(std::vector<_Ty>::size_type, const _Ty &,const _A &)' : cannot convert parameter 1 from 'CFil...

question on std::vector default ctor
In _The C++ Standard Library_ by Josuttis, page 149, is the assertion that std::vector<T> v(5); calls the default ctor of T 5 times. I wrote a test case for this using gcc 3.2, and the default ctor was called only once. Which of the following is true? 1) Josuttis was mistaken 2) The standard has changed 3) This is a gcc 3.2 bug (optimization?) 4) It's due to some other reason I haven't thought of TIA (test program follows) // vectorsize.cpp -- example of sizing a vector #include <vector> using std::vector; #include <iostream> using std::cout; using std::endl;...

multiple threads grabbing items from a vector
Hi. I want to startup 3 threads which will access elements of a Vector and perform an action based upon the value in the vector. I want to each thread to get priority to the Vector to grab the next element in order that the particular thread completed enacting on the previous Vector element. Forinstance, Assuming each thread gets started in order.. The first three elements of the vector would get executed in order Thread 0 ==> element 0 Thread 1 ==> element 1 Thread 2 ==> element 2 However if Thread 1 finished before the others it would grab the next vector element.. Thread 1 ==...

What is wrong with this code?(returning an item in the vector)
Hi, Here is the code that .NET does not seem to like, but as far as i can see it is valid C++ code. Am i wrong? .... // vector headers .... struct MYSTRUCT { int m_iSomething; }; typedef std::vector< MYSTRUCT, std::allocator<MYSTRUCT > > MYSTRUCT_VECTOR; .... // Within class .... MYSTRUCT_VECTOR g_MyVector; int CMyClass::FindSomeThing( int pos ) { // return item } MYSTRUCT * CMyClass::GetStructure( int iSomething) { // Find the item in the vector int pos = FindSomeThing( iSomething ); // Anything found if( pos <0 ) return NULL; // ...

remove items from a vector using iterator
Hi, I want to remove some elements from a vector, the following code doesn't work, seems it doesn't allow me to remove an element when iterating the vector. (make sense), just wonder, how to do this? thank vector<int> IntVec; vector<int>::iterator intIterator; for(int i=0; i<10;i++) IntVec.push_back(i); for(int i=0; i<10;i++) IntVec.push_back(i); for(int i=0; i<10;i++) IntVec.push_back(i); for(intIterator = IntVec.begin(); intIterator !=IntVec.end(); intIterator++) { if(*intIterator == 2) IntVec.erase(intIterator); } happyvalley wrote: >...

Swapping a single pointer item in vector?
Hi all, is there an easy way to swap one pointer item in a vector with a pointer that's not yet in the vector? Currently, I'm using begin()+index to get an iterator to the item I want to swap out, then deleting the pointer there, then using erase to get rid of the vector item itself and get an iterator to the next item, and finally using insert to put my new pointer in the correct place. Is there an easier way? Thanks, -Howard * Howard: > > is there an easy way to swap one pointer item in a vector with a > pointer that's not yet in the vector? st...

Popping the last item in a std::vector
Hi, I am using the std::vector class as follows: vector <myclass *> stack1; and am pushing myclass objects onto the end of the vector like so: myclass *ptr = new myclass(); stack1.push_back(ptr); what I would like to do is pop this item from the end of the vector as well, however the vector::pop_back method does not return anything (it has a void return-type). So my question is, what is the preferred, neatest method to pop the last element from a vector but also retain that value? maybe iterators or direct-access using the operator[], followed by the pop_back call? Basically I'...

Reading items from a text file to a vector
Hi, i need to read a text file which contains a list of items, all of type ItemType, separated by whitespace and newlines. For each line, there will be a vector<ItemType> object that will store the integers read in that line. There will be a single vector<vector<ItemType>> object that will stores all of the vector<ItemType> objects mentioned in the previous sentence. I wrote a quick implementation and it seems to be working, but i would like to hear some opinions on what may be incorrect or may be improved, especially exception and runtime error handling. Assume that t...

Retrieving a class instance item from a vector
Having problem with retrieving a class instance item from a Vector. This is the result of the code below. Also a weird note: If I dont declare as: TYPE_VECTOR_BANKED_MEMORY_DATA bankedDataMemoryLayout(NUMBER_BANKS); but an empty vector TYPE_VECTOR_BANKED_MEMORY_DATA bankedDataMemoryLayout; The program crashes on the 3rd insertion??? Additionally in the printout routine I am having a problem with using an iterator. Can I not use an iterator? PRIMING THE VECTOR: STARTING ADDRESS: [c000] ENDING ADDRESS: [feff] STARTING ADDRESS: [380000] ENDING ADDRESS: [3cbfff] STARTING ADDRESS: ...

how can I find the smallest item in a vector
Hi, Is there a std algorithm which find the smallest item in a vector? One way to do it is to use the sort algorithm and then get the first element. But what if I just care about the smallest, so I don't care if the rest of the vector is sorted according. Is there a more efficient solution to my problem? Thank you. On Feb 20, 8:50 pm, "ken" <ken.carl...@gmail.com> wrote: > Hi, > > Is there a std algorithm which find the smallest item in a vector? > One way to do it is to use the sort algorithm and then get the first > element. > But what if I just car...

vector ctor passed with two arguments of same type
I am copying the following text as it is from Stroustrup's TC++PL 3rd edition, page 450. It says: "Note that a constructor given two arguments of the same type can be a match for more than one constructor. For example, vector<int> v(10, 50); // (size, value) or (iterator1, iterator2)? The problem is that the declaration template <class In> vector<In first, In last, const A& = A()); doesn't actually say that 'In' must be an input iterator. The declaration specifies only that the constructor's two first arguments must be of the same type. The un...

Constant Time std::vector Item Removal
I used to call vector.remove(it+i) to remove the i-th position element in a STL vector, but this causes a O(n) shifting of objects past the deleted item: std::vector<ObjType> vec; ..... // fill with items vec.erase( vec.begin() + pos ); // remove ith pos item Recently, I've been getting good results by simply replacing the soon- to-be-deleted i-th element in the vector by the tail item in the vector, then resizing the vector to originalsize - 1: std::vector<ObjType> vec; ..... // fill with items vec[pos] = vec[ vec.size() -1 ]; vec.resize( vec.size() - 1 )...

Refs. in std::vector, ctor arguments, etc
Hi all, I have a few - beginners - questions: * Why can't I put object references in a std::vector, i.e std::vector<MyClass&> ? At least in doesnt work in gcc (mingw, win32) * What's the difference between passing member inits in the c-tor funtion from doing them as "ordinary" vars? i.e MyClass::MyClass : my_member1 (5), my_member (2) { } as opposed to MyClass::MyClass { my_member1 = 5; my_member = 2; } * I'm looping through a std::vector using iterators. Under some criterias I want to access certain elements of that vector usi...

getting avg of long and std::vector::size_type
I'm trying to get an average of a long and a std::vector::size_type, but keep getting 0 for some reason. I've tried the following: float avg = some_long / some_vec.size(); float avg = some_long / static_cast<long>(some_vec.size()); Both produce 0. Anyone able to give me a hint at what I'm doing wrong? Aaron wrote: > I'm trying to get an average of a long and a std::vector::size_type, but > keep getting 0 for some reason. > > I've tried the following: > > float avg = some_long / some_vec.size(); > float avg = some_long / static_cast<long...