473,396 Members | 1,866 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

how to initialize std::vector?

JDT
Hi,

Can someone show me how to set any integer (or float) in an std::vector
as zero in a way other than using a for loop? Can we apply memset() or
ZeroMemory() to the vector? Thanks for your help.

JD
Jan 20 '07 #1
16 25980
JDT wrote:
Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?
No.

vector<floatmyvector;
... // fill myvector with something

vector<float>(myvector.size(), 0f).swap(myvector);

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 20 '07 #2
* JDT:
>
Can someone show me how to set any integer (or float) in an std::vector
as zero in a way other than using a for loop?
Note that any way you do it, there will be a loop, at some level of the
implementation.

An easy but perhaps not the most efficient way for a vector v of type V is

V( v.size() ).swap( v );

Or you can do e.g.

std::fill( v.begin(), v.end(), 0 );

Can we apply memset() or
ZeroMemory() to the vector?
std::memset can be applied to a vector of POD element type, but it's not
recommended, especially not for one who is in doubt about its usage.

ZeroMemory is not a standard C++ function.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jan 20 '07 #3
"JDT" <jd*******@yahoo.comwrote in message
news:ZK*******************@newssvr14.news.prodigy. net...
Hi,

Can someone show me how to set any integer (or float) in an std::vector as
zero in a way other than using a for loop? Can we apply memset() or
ZeroMemory() to the vector? Thanks for your help.

JD
You *could* use memset, but personally I don't like it. The reason being it
can break classes.

Say, for instance you have a std::vector of a simple POD class such as:

class MyClass
{
public:
int MyInt;
float MyFloat;
char MyChar;
};

std::vector<MyClassMyVector;

So you go ahead and use memset something like (this may be off):

memset( &MyVector[0], 0, sizeof MyClass * MyVector.count() );

Okay, it works for now. But maybe later you change MyClass to also include
something that's not POD.

class MyClass
{
public:
int MyInt;
float MyFloat;
char MyChar;
std::string MyString;
};

the memset will still set the variables to 0, but now you just broke
MyString. MyString has a constructor that sets all kinds of things such as
pointers that aren't necessarily 0.

Consider alternatives.
Jan 20 '07 #4
JDT <jd*******@yahoo.comwrote:
Can someone show me how to set any integer (or float) in an std::vector
as zero in a way other than using a for loop? Can we apply memset() or
ZeroMemory() to the vector? Thanks for your help.
You could just assign 0 to the element you want to set. If you meant
"every" instead of "any". There are several ways:

a) The vector/swap trick that Victor & Alf showed.
b) The std::fill algorithm that Alf showed.

You could also:

unsigned s = vec.size();
vec.clear();
vec.resize( s );
Jan 20 '07 #5
Victor Bazarov wrote:
JDT wrote:
>Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?

No.
Hmmm.... the question says how to initialize the vector. So would not
this satisfy the question:

std::vector<intv;
v.resize(100);

Thus creating 100 elements that are all default initialized, or 0
initialized in the case of ints.

--
Ivan
http://www.0x4849.net
Jan 20 '07 #6
"Ivan Novick" <iv**@0x4849.netwrote in message
news:Qu******************@newssvr21.news.prodigy.n et
Victor Bazarov wrote:
>JDT wrote:
>>Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?

No.
Hmmm.... the question says how to initialize the vector. So would not
this satisfy the question:

std::vector<intv;
v.resize(100);

Thus creating 100 elements that are all default initialized, or 0
initialized in the case of ints.
If it's initialization, then

std::vector<intv(100);

will do it without a resize.
--
John Carson
Jan 20 '07 #7
"JDT" <jd*******@yahoo.comwrote in message
news:ZK*******************@newssvr14.news.prodigy. net
Hi,

Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector? Thanks for your help.

JD

For a vector with 100 zeros:

vector<intv(100,0);
--
John Carson
Jan 20 '07 #8
"John Carson" <jc****************@netspace.net.auwrote in message
news:45***********************@uv-55king-reader-01.melbourne.pipenetworks.com.au
"JDT" <jd*******@yahoo.comwrote in message
news:ZK*******************@newssvr14.news.prodigy. net
>Hi,

Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector? Thanks for your help.

JD


For a vector with 100 zeros:

vector<intv(100,0);
vector<intv(100);

will also do it, but the OP may not want initialization.
--
John Carson
Jan 20 '07 #9
Ivan Novick wrote:
Victor Bazarov wrote:
>JDT wrote:
>>Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?

No.
Hmmm.... the question says how to initialize the vector.
No, it doesn't. It asks how to "set any integer".
So would not
this satisfy the question:

std::vector<intv;
v.resize(100);

Thus creating 100 elements that are all default initialized, or 0
initialized in the case of ints.
Just to explain to those who missed it, the "no" is for the last
question (about 'memset' or 'ZeroMemory' application to a vector).
I hope it's clearer now.

My answer to how to set the contents of the vector to 0 was given
in the same message and for whatever reason snipped away by Ivan.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 20 '07 #10
Victor Bazarov wrote:
Just to explain to those who missed it, the "no" is for the last
question (about 'memset' or 'ZeroMemory' application to a vector).
I hope it's clearer now.

My answer to how to set the contents of the vector to 0 was given
in the same message and for whatever reason snipped away by Ivan.

V
Strictly speaking, I believe it is (technically) legal
to use memset() starting at &(vector_of_int[0]) to set
the values of the vector's elements to some values
(admittedly, those who's representation consists of equal bytes).

So it would be (technically) legal to zero-initialize a
vector of ints like that, no?

Though I'd bet the default-initialization does exactly
that.

- J.
Jan 20 '07 #11
Victor Bazarov wrote:
Ivan Novick wrote:
>Victor Bazarov wrote:
>>JDT wrote:
Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?
No.
Hmmm.... the question says how to initialize the vector.

No, it doesn't. It asks how to "set any integer".
The subject of the message is how to initialize.

In which case I would say John Carson's reply is the best:

std::vector<intv(100);
Just to explain to those who missed it, the "no" is for the last
question (about 'memset' or 'ZeroMemory' application to a vector).
I hope it's clearer now.

My answer to how to set the contents of the vector to 0 was given
in the same message and for whatever reason snipped away by Ivan.
Woops, overzealous snipping on my part. Sorry.

--
Ivan
http://www.0x4849.net
Jan 20 '07 #12
Jacek Dziedzic wrote:
Victor Bazarov wrote:
>Just to explain to those who missed it, the "no" is for the last
question (about 'memset' or 'ZeroMemory' application to a vector).
I hope it's clearer now.

My answer to how to set the contents of the vector to 0 was given
in the same message and for whatever reason snipped away by Ivan.

V

Strictly speaking, I believe it is (technically) legal
to use memset() starting at &(vector_of_int[0]) to set
the values of the vector's elements to some values
(admittedly, those who's representation consists of equal bytes).

So it would be (technically) legal to zero-initialize a
vector of ints like that, no?

Though I'd bet the default-initialization does exactly
that.
Just to clarify -- I obviously meant the case where the
vector is large enough (resized appropriately) so that the
memset does not trash what comes after the vector.

- J.
Jan 21 '07 #13
Jacek Dziedzic wrote:
Jacek Dziedzic wrote:
>Victor Bazarov wrote:
>>Just to explain to those who missed it, the "no" is for the last
question (about 'memset' or 'ZeroMemory' application to a vector).
I hope it's clearer now.

My answer to how to set the contents of the vector to 0 was given
in the same message and for whatever reason snipped away by Ivan.

V

Strictly speaking, I believe it is (technically) legal
to use memset() starting at &(vector_of_int[0]) to set
the values of the vector's elements to some values
(admittedly, those who's representation consists of equal bytes).

So it would be (technically) legal to zero-initialize a
vector of ints like that, no?

Though I'd bet the default-initialization does exactly
that.

Just to clarify -- I obviously meant the case where the
vector is large enough (resized appropriately) so that the
memset does not trash what comes after the vector.
I wouldn't bet the default initialisation does that, but it is most
likely safe to do with vectors of POD.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Jan 22 '07 #14

Jim Langston skrev:
"JDT" <jd*******@yahoo.comwrote in message
news:ZK*******************@newssvr14.news.prodigy. net...
Hi,

Can someone show me how to set any integer (or float) in an std::vector as
zero in a way other than using a for loop? Can we apply memset() or
ZeroMemory() to the vector? Thanks for your help.

JD

You *could* use memset, but personally I don't like it. The reason being it
can break classes.

Say, for instance you have a std::vector of a simple POD class such as:

class MyClass
{
public:
int MyInt;
float MyFloat;
char MyChar;
};

std::vector<MyClassMyVector;

So you go ahead and use memset something like (this may be off):

memset( &MyVector[0], 0, sizeof MyClass * MyVector.count() );

Okay, it works for now.
[snip]

That depends on what you mean when it works. You can't expect MyFloat
to be zero - although it likely is on your platform, and I am not even
sure that you can expect MyInt or MyChar to be zero. (I do not believe
a number format where "all zeros" means lowest possible value is
nonconforming).

/Peter

Jan 22 '07 #15
peter koch wrote:
>
Jim Langston skrev:
>"JDT" <jd*******@yahoo.comwrote in message
news:ZK*******************@newssvr14.news.prodigy .net...
Hi,

Can someone show me how to set any integer (or float) in an std::vector
as
zero in a way other than using a for loop? Can we apply memset() or
ZeroMemory() to the vector? Thanks for your help.

JD

You *could* use memset, but personally I don't like it. The reason being
it can break classes.

Say, for instance you have a std::vector of a simple POD class such as:

class MyClass
{
public:
int MyInt;
float MyFloat;
char MyChar;
};

std::vector<MyClassMyVector;

So you go ahead and use memset something like (this may be off):

memset( &MyVector[0], 0, sizeof MyClass * MyVector.count() );

Okay, it works for now.
[snip]

That depends on what you mean when it works. You can't expect MyFloat
to be zero - although it likely is on your platform, and I am not even
sure that you can expect MyInt or MyChar to be zero. (I do not believe
a number format where "all zeros" means lowest possible value is
nonconforming).
From the standard

[3.9.1/7]

[...] The representations of integral types shall define values by use of
a pure binary numeration system.44) [...]

[44] A positional representation for integers that uses the binary digits
0 and 1, in which the values represented by successive bits are additive,
begin with 1, and are multiplied by successive integral power of 2, except
perhaps for the bit with the highest position.
(Adapted from the American National Dictionary for Information Processing
Systems.)

[3.9.1/8]

[...] The value representation of floating-point types is
implementation-defined. [...]
Best

Kai-Uwe Bux
Jan 22 '07 #16

Victor Bazarov wrote:
JDT wrote:
Can someone show me how to set any integer (or float) in an
std::vector as zero in a way other than using a for loop? Can we
apply memset() or ZeroMemory() to the vector?

No.
Actually, you can. It bypasses much of the safety of using a vector
but with care it can be done.

std::vector<intx;
x.resize(100);

memset(&v[0], 0, sizeof(int) * 100);

Of course, there isn't much reason to do this (since resize() already
did it in a more well defined manner), but it *can* be done. There are
many other times when such techniques are reasonable even if rather
dangerous. Any time you need a buffer of some type a std::vector can
be used in place; you can pass &v[0] and know that, assuming you've
told the vector to allocate enough room, it will do what you expect.

Jan 22 '07 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: enzo | last post by:
hi all, i don't understand what's wrong: 1) std::vector<double> p(10); doesn't compile:
16
by: Honestmath | last post by:
Hi, I added the following line to my code within a class declaration: std::vector<Date> m_duedates(100); I also tried: std::vector<Date> m_duedates(100, Date());
20
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; ...
12
by: cppaddict | last post by:
I'm confused about const references. I thought they provided a way to give access to private members without allowing those members to be changed. However, the following client code successfully...
3
by: Pelle Beckman | last post by:
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...
2
by: zl2k | last post by:
hi, all Suppose I have the following header file: #include <vector> using namespace std; class Test{ public: ~Test(); Test();
4
by: mathieu | last post by:
Hello, I am looking at the API of std::vector but I cannot find a way to specify explicitely the size of my std::vector. I would like to avoid vector::resize since it first initializes the...
9
by: aaragon | last post by:
I am trying to create a vector of type T and everything goes fine until I try to iterate over it. For some reason, the compiler gives me an error when I declare std::vector<T>::iterator iter;...
2
by: Tony Young | last post by:
Hi, I wonder if there is a way to declare and initialize a vector in one line as one does for array (shown below): int n = {1, 2, 3, 4}; The one line should be equivalent to the following...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.