473,698 Members | 2,833 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector assign

Hi all, personally I'd love to be able to do something like this:

vector<intv;
v.assign(1, 2, 5, 9, 8, 7) etc

without having to manually add elements by doing v[0] = 1, v[1] = 2 ..
etc.

it would make for much more readable code that is faster to write in
some situations. I've not seen this feature documented anywhere
though which I find curious. is there another way to achieve this?

thanks,
stephen.
Jun 27 '08 #1
29 3416
stephen b wrote:
it would make for much more readable code that is faster to write in
some situations. I've not seen this feature documented anywhere
though which I find curious. is there another way to achieve this?
Maybe using variable arguments and inheritance

#include <iostream>
#include <vector>
#include <stdarg.h>
#include <iterator>

template <typename T class myVec: public std::vector<T>
{
public:
void assign(int amount,...);
};

template <typename T void myVec<T>::assig n(int amount,...)
{
T val;
va_list vl;
va_start(vl,amo unt);
for (int i=0;i<amount;i+ +)
{
val=va_arg(vl,T );
push_back(val);
}
va_end(vl);
}

int main()
{

myVec<intvec;
vec.assign(3,2, 1,0);
std::copy(vec.b egin(),vec.end( ),std::ostream_ iterator<int>(s td::cout,
" "));
return 0;
}

Darío
Jun 27 '08 #2
In article
<25************ *************** *******@k37g200 0hsf.googlegrou ps.com>,
Darío Griffo <da************ *****@gmail.com wrote:
stephen b wrote:
it would make for much more readable code that is faster to write in
some situations. I've not seen this feature documented anywhere
though which I find curious. is there another way to achieve this?

Maybe using variable arguments and inheritance

#include <iostream>
#include <vector>
#include <stdarg.h>
#include <iterator>

template <typename T class myVec: public std::vector<T>
{
public:
void assign(int amount,...);
};

template <typename T void myVec<T>::assig n(int amount,...)
{
T val;
va_list vl;
va_start(vl,amo unt);
for (int i=0;i<amount;i+ +)
{
val=va_arg(vl,T );
push_back(val);
}
va_end(vl);
}

int main()
{

myVec<intvec;
vec.assign(3,2, 1,0);
std::copy(vec.b egin(),vec.end( ),std::ostream_ iterator<int>(s td::cout,
" "));
return 0;
}

Darío
Would this work for non-POD types? BTW inheritance is not necessary.

template < typename T >
void assign( std::vector<T>& vec, int count, ... )
{
va_list vl;
va_start( vl, count );
for ( int i=0; i!= count; ++i)
{
vec.push_back( va_arg( vl, T ) );
}
va_end(vl);
}

using namespace std;

int main()
{
vector<intvec;
assign( vec, 3, 2, 1, 0 );
copy( vec.begin(), vec.end(), ostream_iterato r<int>( cout, " " ) );
}

}
Jun 27 '08 #3
On May 23, 3:40 pm, stephen b <ker...@audiosp illage.comwrote :
Hi all, personally I'd love to be able to do something like this:

vector<intv;
v.assign(1, 2, 5, 9, 8, 7) etc
Checkout Boost's Assign Library. You can do these:

vector<intv;
v += 1,2,3,4,5,6,7,8 ,9;

or

vector<intv = list_of(1)(2)(3 );

etc.

Ali

Jun 27 '08 #4
On May 23, 5:48*pm, acehr...@gmail. com wrote:
On May 23, 3:40 pm, stephen b <ker...@audiosp illage.comwrote :
Hi all, personally I'd love to be able to do something like this:
vector<intv;
v.assign(1, 2, 5, 9, 8, 7) etc

Checkout Boost's Assign Library. You can do these:

vector<intv;
v += 1,2,3,4,5,6,7,8 ,9;

or

vector<intv = list_of(1)(2)(3 );
Thanks, that looks really promising, I'll check it out. Stephen.
Jun 27 '08 #5


Daniel T. wrote:
Would this work for non-POD types?
A simple test told me not :(

compiling test.cpp (g++)
test.cpp:65: instantiated from here
test.cpp:56: warning: cannot receive objects of non-POD type 'class A'
through '...'; call will abort at runtime
BTW inheritance is not necessary.

I know, but since we program in OOP paradigm, it seems to me the best
way to do that.
>
template < typename T >
void assign( std::vector<T>& vec, int count, ... )
{
va_list vl;
va_start( vl, count );
for ( int i=0; i!= count; ++i)
{
vec.push_back( va_arg( vl, T ) );
}
va_end(vl);
}

using namespace std;

int main()
{
vector<intvec;
assign( vec, 3, 2, 1, 0 );
copy( vec.begin(), vec.end(), ostream_iterato r<int>( cout, " " ) );
}

}
Jun 27 '08 #6
In article <54590b15-eafb-45ca-83ac-3768a65f8e65@
2g2000hsn.googl egroups.com>, ke****@audiospi llage.com says...
Hi all, personally I'd love to be able to do something like this:

vector<intv;
v.assign(1, 2, 5, 9, 8, 7) etc

without having to manually add elements by doing v[0] = 1, v[1] = 2 ..
etc.

it would make for much more readable code that is faster to write in
some situations. I've not seen this feature documented anywhere
though which I find curious. is there another way to achieve this?
If you have a predefined set of elements (and that's all the vector will
need to hold) you might want to look into using TR1::array instead of a
vector (the same class is in the current draft for C++ 0x as std::array
as well).

If you will/might need to expand the collection later, you'll still need
to use a vector, but you can initialize the array from the constants,
and then initialize the vector from the array:

TR1::array<inta = {1, 2, 5, 9, 8, 7};

std::vector<int >v(a.begin(), a.end());

That may not be perfect, but it's still pretty decent.

There have been a number of other methods invented, but none of them is
particularly clean. I once wrote a bit of code to deal with this
problem, but it's sufficiently ugly that I never use it myself, so I'd
have some difficulty recommending that anybody else do so either:

template<class T>
class fill_vector {
std::vector<Tda ta;
public:
fill_vector(T const &val) {
data.push_back( val);
}

fill_vector<T&o perator,(T const &t) {
data.push_back( t);
return *this;
}

operator std::vector<T>( ) { return data; }
};

template<class T>
fill_vector<Tfi llVect(T const &t) {
return fill_vector<T>( t);
}

std::vector<int iv = (fillVect(1), 2, 5, 9, 8, 7);

I wouldn't mind if the code for fill_vector or fill_vect was ugly, but
the code to use them needs those seemingly extraneous parentheses, so
the code that uses this technique is unavoidably rather ugly. That
really _does_ bother me.

Another direction is to start with an array, and just have a reasonably
clean way of supplying iterators to the beginning and end of the array
so you can initialize the vector from it cleanly:

template <class T, size_t N>
T *end(T (&input)[N]) {
return input+N;
}

int init[] = { 1, 2, 5, 9, 8, 7};

std::vector<int v(init, end(init));

Like the version that initializes a vector from a TR1::array, this
separates creation of the vector from defining its initial data, and
requires a name for the object holding that initial data. That's not
really ideal, but in practice I've never really run into a major problem
with it either.

Choosing between TR1::array and/or std::array and this last version,
isn't necessarily simple. If you already have the array class available
(on all compilers you need to target), you might as well use it. If you
don't have it available, you need to decide whether the number of times
you could use an array object directly (rather than just to initialize a
vector) justifies finding and installing an implementation. That'll
depend on circumstances about which I know too little to comment
intelligently.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jun 27 '08 #7
On May 24, 1:48 am, acehr...@gmail. com wrote:
On May 23, 3:40 pm, stephen b <ker...@audiosp illage.comwrote :
Hi all, personally I'd love to be able to do something like this:
vector<intv;
v.assign(1, 2, 5, 9, 8, 7) etc
Checkout Boost's Assign Library. You can do these:
vector<intv;
v += 1,2,3,4,5,6,7,8 ,9;
Institutionaliz ed obfuscation, anyone? That statement has a
predefined meaning in C++, without any library, and any code
which changes a predefined meaning should be avoided at all
costs.
or
vector<intv = list_of(1)(2)(3 );
That's better. A lot of the time, of course, simply:

static int const init[] = { 1, 2, 5, 9, 8, 7 } ;
std::vector< int v( begin( init ), end( init ) ) ;

is just as good.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #8
On May 24, 8:01 am, Jerry Coffin <jcof...@taeus. comwrote:
In article <54590b15-eafb-45ca-83ac-3768a65f8e65@
2g2000hsn.googl egroups.com>, ker...@audiospi llage.com says...
If you will/might need to expand the collection later, you'll
still need to use a vector, but you can initialize the array
from the constants, and then initialize the vector from the
array:
TR1::array<inta = {1, 2, 5, 9, 8, 7};
Can TR1::array deduce the length from the number of elements in
the initialization list? (And if so, how?)

IIUC, the standard is extending initialization syntax
expressedly to deal with such cases (and will allow an
initialization list directly in the definition of the vector),
but I didn't think that it could be done today.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34
Jun 27 '08 #9
Hi!

DarÃ*o Griffo schrieb:
>BTW inheritance is not necessary.

I know, but since we program in OOP paradigm, it seems to me the best
way to do that.
No. It is not the best way although we have "OOP" at our disposal (I
think of "OOP" here as "derive from a base class"). A vector makes no
good base class. You must not derive from it. Value based classes are
usually not suited for inheritance. Think of a "long" derived from an
"int"!?

A better way to do it is to write a complete wrapper and add
functionality as needed:

template<typena me T>
class AssignableVecto r
{
vector<Tdata;
public:
AssignableVecto r() {}
AssignableVecto r(size_t n, T const t = T())
: data(n, t)
{}
//forward all functions to the vector:
void push_back(T const t) { data.push_back( t); }
...

//add extra functionality:
void assign(/*whatever parameters are needed*/) { ... }
};

This it much code. And it is boring to write. I guess that's why many
people resort to inheritance: just to save typing.

When I can't really convince you not to use inheritance, then at least
use private inheritance to hide it. (Which means you would have to
somehow provide public versions of the inherited methods, which needs
the same typing than above after all).

Regards,
Frank
Jun 27 '08 #10

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

Similar topics

5
7387
by: scooter | last post by:
what happens memory wise with this scenerio: std::vector<int> vecInt(20, 999); VecInt.assign(20, 0); do all the 999 values get overwritten or does the vector reassign the memory lso?
11
2429
by: nandor.sieben | last post by:
I am trying to replace template < class T void set2vector (const set < T &s, vector < T &v) { typename set < T >::iterator it; for (it = s.begin (); it != s.end (); it++) { v.push_back (*it); } }
4
6947
by: Chris Roth | last post by:
vector<doublev1(5,1); vector<doublev2; v2 = v1; // 1 v2.assign(v1.begin(),v1.end()); // 2 Are 1 and 2 the same, or are their subtle differences between them. Which is preferable, if either? And yes, I know I could use the construction vector<doublev2(v1), but I'm giving an example above.
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8611
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9031
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8876
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7741
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.