473,396 Members | 1,940 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.

Initializing a vector with pointers to elements of another

Hi,

say I have a vector v1:

std::vector<SomeType> v1;

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

std::vector<SomeType*> v2;

std::vector<SomeType>::iterator 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 3091
"Matthias" <no****@digitalraid.com> wrote in message
news:cu*************@news.t-online.com...
Hi,

say I have a vector v1:

std::vector<SomeType> v1;

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

std::vector<SomeType*> v2;

std::vector<SomeType>::iterator 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::vector<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(vec.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_inserter(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<SomeType> v1;

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

std::vector<SomeType*> v2;

std::vector<SomeType>::iterator 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()(SomeType& s) const { return &s; }
const SomeType* operator()(const SomeType& s) const { return &s; }
};

/// ...

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

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

say I have a vector v1:

std::vector<SomeType> v1;

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

std::vector<SomeType*> v2;

std::vector<SomeType>::iterator 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()(SomeType& s) const { return &s; }
const SomeType* operator()(const SomeType& s) const { return &s; }
};

/// ...

std::transform(v1.begin(), v1.end(),
std::back_inserter(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<SomeType>::size_type> v2;

for (std::vector<SomeType>::size_type> 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.programming 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.programming 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.programming 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
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...
9
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...
14
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...
34
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...
11
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
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...
3
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...
19
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....
2
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. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
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
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...
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.