473,837 Members | 1,682 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initializing a vector with pointers to elements of another

Hi,

say I have a vector v1:

std::vector<Som eType> v1;

and I need a vector v2 of pointers to v1's elements:

std::vector<Som eType*> v2;

std::vector<Som eType>::iterato r iter;
for( iter = v1.begin(); iter != v1.end(), ++iter )
v2.push_back( &(*iter) );
Now is there a more elegant way to initialize v2 instead of looping
through v1 and pushing back the *iter's address to v2?
Something like "for each elem in v1 insert its address into v2"?
Having a loop which only consists of a single insert operation, I have
the feeling this may be better expressed with some STL algo.

--
Regards,
Matthias
Jul 23 '05 #1
6 3132
"Matthias" <no****@digital raid.com> wrote in message
news:cu******** *****@news.t-online.com...
Hi,

say I have a vector v1:

std::vector<Som eType> v1;

and I need a vector v2 of pointers to v1's elements:

std::vector<Som eType*> v2;

std::vector<Som eType>::iterato r iter;
for( iter = v1.begin(); iter != v1.end(), ++iter )
v2.push_back( &(*iter) );
Now is there a more elegant way to initialize v2 instead of looping
through v1 and pushing back the *iter's address to v2?
Something like "for each elem in v1 insert its address into v2"?
Having a loop which only consists of a single insert operation, I have
the feeling this may be better expressed with some STL algo.


You could use 'std::for_each( )' with a functor, but imo it's
probably not worth the trouble. You might just want to wrap
that loop up into a function with references to the two vectors
as parameters, then just call from your 'main' logic. Here's the
'for_each' code just for fun anyway:
#include <algorithm>
#include <vector>

class ftor
{
std::vector<int *>& v;
public:
ftor(std::vecto r<int*>& arg) : v(arg)
{
}

void operator()(int& i)
{
v.push_back(&i) ;
}
};

int main()
{
std::vector<int > vec;
for(int i = 0; i < 5; ++i)
vec.push_back(i );

std::vector<int *> pvec;
std::for_each(v ec.begin(), vec.end(), ftor(pvec));

return 0;
}

Another possiblity (if your element type is user-defined), is
to define a conversion from T to T*, and use 'std::copy' (not
possible if the element type is a built-in type):

#include <algorithm>
#include <vector>

class C
{
public:
operator C*()
{
return this;
}
};

int main()
{
std::vector<C> cvec;
for(int i = 0; i < 5; ++i)
{
cvec.push_back( C());
}

std::vector<C*> pvec;

std::copy(cvec. begin(), cvec.end(),
std::back_inser ter(pvec));

return 0;
}

However I consider this dangerous, as the automatic conversion
from C to C* could mask errors elsewhere.

Having said all the above, BE WARNED: No matter which way you
store your pointers (with a 'plain' loop, either of the ways
I've shown, or any other way), note that if you later modify
the vector of whose elements you're storing their addresses,
and the vector is later modified, the elements could be moved
due to reallocation, invalidating the address values stored
in the other vector. I'd consider doing what you're
asking about only if the first vector is const (in which
case you'd have to load it via a ctor, since you wouln't
be able to 'push_back' the elements. Or if it's not const,
you'd need to reset and reload the pointer vector every time
the first vector gets changed. An awful lot of work. :-)

-Mike
Jul 23 '05 #2
Matthias wrote:
Hi,

say I have a vector v1:

std::vector<Som eType> v1;

and I need a vector v2 of pointers to v1's elements:

std::vector<Som eType*> v2;

std::vector<Som eType>::iterato r iter;
for( iter = v1.begin(); iter != v1.end(), ++iter )
v2.push_back( &(*iter) );
Now is there a more elegant way to initialize v2 instead of looping
through v1 and pushing back the *iter's address to v2?
Something like "for each elem in v1 insert its address into v2"?
Having a loop which only consists of a single insert operation, I have
the feeling this may be better expressed with some STL algo.


struct addressor {
SomeType* operator()(Some Type& s) const { return &s; }
const SomeType* operator()(cons t SomeType& s) const { return &s; }
};

/// ...

std::transform( v1.begin(), v1.end(),
std::back_inser ter(v2),
addressor());

Jul 23 '05 #3
red floyd wrote:
Matthias wrote:
Hi,

say I have a vector v1:

std::vector<Som eType> v1;

and I need a vector v2 of pointers to v1's elements:

std::vector<Som eType*> v2;

std::vector<Som eType>::iterato r iter;
for( iter = v1.begin(); iter != v1.end(), ++iter )
v2.push_back( &(*iter) );
Now is there a more elegant way to initialize v2 instead of looping
through v1 and pushing back the *iter's address to v2?
Something like "for each elem in v1 insert its address into v2"?
Having a loop which only consists of a single insert operation, I have
the feeling this may be better expressed with some STL algo.


struct addressor {
SomeType* operator()(Some Type& s) const { return &s; }
const SomeType* operator()(cons t SomeType& s) const { return &s; }
};

/// ...

std::transform( v1.begin(), v1.end(),
std::back_inser ter(v2),
addressor());


That said, storing *addresses* of vector elements is a "bad idea"(tm).
You have the same problem as storing iterators to the elements -- they
can be invalidated should the vector need to reallocate itself.
Better to store the indices instead. i.e.

std::vector<std ::vector<SomeTy pe>::size_type> v2;

for (std::vector<So meType>::size_t ype> i = 0 ; i < v1.size(); ++i)
v2.push_back(i) ;
Jul 23 '05 #4
Thanks for your answers.

As to the overall pointer question:
I want to store pointers, because I need to sort the elements, and I
thought I'd be better to sort pointers instead of the objects themselves
for performance reasons. At least that's what the guys over at
comp.programmin g suggested.

On the other hand, the actual objects are boost pathS, which only
consist of a single string object IIRC (the rest of the path class are
operations).

Is it worth the inconvenience at all to sort pointers to path objects
instead of sorting the pathS themselves? How expensive is it to copy a
path object?

--
Regards,
Matthias
Jul 23 '05 #5

Matthias wrote:
Thanks for your answers.

As to the overall pointer question:
I want to store pointers, because I need to sort the elements, and I
thought I'd be better to sort pointers instead of the objects themselves for performance reasons. At least that's what the guys over at
comp.programmin g suggested.
Well, over here we'd say, profile, and optimize only if needed, and
then profile again to check you actually gained something.

The problem is that swapping two T's may be more expensive then
checking two T*s, but this is not always the case. In particular,
swapping two strings or similar objects is often just as expensive:
a common string implementation is just a pointer+size. Swapping those
is twice the work of swapping two pointers, which is balanced by
the reduction in indirection.
Is it worth the inconvenience at all to sort pointers to path objects instead of sorting the pathS themselves? How expensive is it to copy a path object?


Doesn't matter much, the price of swaps tends to dominate.

HTH,
Michiel Salters

Jul 23 '05 #6
msalters wrote:
Matthias wrote:
Thanks for your answers.

As to the overall pointer question:
I want to store pointers, because I need to sort the elements, and I
thought I'd be better to sort pointers instead of the objects


themselves
for performance reasons. At least that's what the guys over at
comp.programm ing suggested.

Well, over here we'd say, profile, and optimize only if needed, and
then profile again to check you actually gained something.

The problem is that swapping two T's may be more expensive then
checking two T*s, but this is not always the case. In particular,
swapping two strings or similar objects is often just as expensive:
a common string implementation is just a pointer+size. Swapping those
is twice the work of swapping two pointers, which is balanced by
the reduction in indirection.

Is it worth the inconvenience at all to sort pointers to path objects


instead of sorting the pathS themselves? How expensive is it to copy


a
path object?

Doesn't matter much, the price of swaps tends to dominate.

HTH,
Michiel Salters


So, there's no reason to sort a list of pointers, because the sort
itself is expensive for both path and "pointer to path"?
Is that what you mean?

--
Regards,
Matthias
Jul 23 '05 #7

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

Similar topics

1
19612
by: TF | last post by:
I have a fixed array of vectors like: vector<string> a_vStr; Then I grow each vector item and use it later. Everything works fine but I am curious about following potential problem. When we grow a vector it may copy all of its elements to different memory location to accomodate the new vector size. Is it possible that at some point an element of fixed array e.g. a_vStr gets invalid or
9
2980
by: luigi | last post by:
Hi, I am trying to speed up the perfomance of stl vector by allocating/deallocating blocks of memory manually. one version of the code crashes when I try to free the memory. The other version seem to work. I would appreciate someone to comment on this. Version 1 (crashes on deallocating) #include <iostream>
14
3540
by: Roland Bengtsson | last post by:
I have a class Conception and I have this in a vector, it should be: vector<Conception> vek; // vector vector<Conception>::iterator vek; // iterator to vek But what if I want to have pointers to class Conception instead? How can I do that? And how should I write to declare an iterator to this vector?
34
4189
by: Adam Hartshorne | last post by:
Hi All, I have the following problem, and I would be extremely grateful if somebody would be kind enough to suggest an efficient solution to it. I create an instance of a Class A, and "push_back" a copy of this into a vector V. This is repeated many times in an iterative process. Ok whenever I "push_back" a copy of Class A, I also want to assign a pointer contained in an exisiting instance of a Class B to this
11
2753
by: koperenkogel | last post by:
Dear cpp-ians, I am working with a vector of structures. vector <meta_segment> meta_segm (2421500); and the structure look like: struct meta_segment { float id; float num;
8
5123
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value types or std::vector<int>. So where I would use an int* and reallocate it from time to time in C, and randomly access it via , then I figure to copy the capacity and reserve methods, because I just need a growable array. I get to considering...
3
5860
by: eriwik | last post by:
I use the following structure to store filenames for one or more "sets" grouped together by a number: map<int, map<string> > fileSets; As arguments to the constructor I send a vector<vector<string> > where each vector<string> contains the filenames of one set. The function getNumber() calculates a number from the filename. The constructor then looks like this:
19
6093
by: arnuld | last post by:
/* C++ Primer - 4/e * chapter 4- Arrays & Pointers, exercise 4.28 * STATEMENT * write a programme to read the standard input and build a vector of integers from values that are read. allocate an array of the same size as the vector and copy elements from the vector into the array */
2
1575
by: =?iso-8859-1?B?Tm9yZGz2dw==?= | last post by:
Hey there, C++ Coders. Does anyone know of a C++ (template) (vector) container that packs its elements based on their relative minimum and maximum value (offset and span) and (minimum) stride. Example: The pointers when packed should be stored internally in the template<Tcontainer as T min: 0
0
9830
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
9682
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
10864
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10615
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10263
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...
1
7803
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...
0
5664
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5842
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3122
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.