473,799 Members | 2,936 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Working with vectors

Hi all,

I have a few question regarding standard C++ and the use of vectors.

Imagine:
void foo(vector<int> x);
vector<int> c;
vector<int> x;

----------

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?

If so, then I wish this to be more efficient so I should probably pass
a reference right? How can I do this in both cases? In calling foo, how
can I make sure the body of foo won't try to change x? (probably const&
or &const, but I never know...)

Cheers,

Paulo Matos

Jul 23 '05 #1
9 1650
pmatos wrote:
Hi all,

I have a few question regarding standard C++ and the use of vectors.

Imagine:
void foo(vector<int> x);
vector<int> c;
vector<int> x;

----------

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?
Yes.
If so, then I wish this to be more efficient so I should probably pass
a reference right?
Yes.
How can I do this in both cases?
For the first case, you can't unless you declare c as a reference to
vector<int> and initialize it with c.
In calling foo, how can I make sure the body of foo won't try to change x?
Let it take a refernce to const vector<int>.
(probably const& or &const, but I never know...)


const vector<int>&. The & is always the last part.

Jul 23 '05 #2
"pmatos" <po**@sat.ine sc-id.pt> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
Hi all,

I have a few question regarding standard C++ and the use of vectors.

Imagine:
void foo(vector<int> x);
vector<int> c;
vector<int> x;

----------

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?

If so, then I wish this to be more efficient so I should probably pass
a reference right? How can I do this in both cases? In calling foo, how
can I make sure the body of foo won't try to change x? (probably const&
or &const, but I never know...)

Cheers,

Paulo Matos


What Rolf said. But I would add one more thing: if all you really need is a
sequence of values, consider writing foo
as

template <typename ITER>
foo(ITER first, ITER last);

Then you can call it with

foo(my_vector.b egin(), my_vector.end() );

but also

foo(my_list.beg in(), my_list.end());

This technique is used extensively in the standard library (see <algorithms>
for instance) because it is both efficient and flexible.

--
Cy
http://home.rochester.rr.com/cyhome/
Jul 23 '05 #3


Rolf Magnus wrote:
pmatos wrote:
Hi all,

I have a few question regarding standard C++ and the use of vectors.

Imagine:
void foo(vector<int> x);
vector<int> c;
vector<int> x;

----------

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?


Yes.
If so, then I wish this to be more efficient so I should probably pass
a reference right?


Yes.
How can I do this in both cases?


For the first case, you can't unless you declare c as a reference to
vector<int> and initialize it with c.


It's not that you can't. The copy constructor for std::vector already
takes a non-modifiable reference to the object being copied. So,

c = x;

calls 'c's copy constructor with a const reference to 'x'. 'x' is not
copied to a temporary, as is the case with 'foo'; only the value of 'x'
is copied to 'c'. The call is already as efficient as it can be.

/david

Jul 23 '05 #4
da********@warp mail.net wrote:


Rolf Magnus wrote:
pmatos wrote:
> Hi all,
>
> I have a few question regarding standard C++ and the use of vectors.
>
> Imagine:
> void foo(vector<int> x);
> vector<int> c;
> vector<int> x;
>
> ----------
>
> What happens when I do:
> c = x;
>
> and
> foo(x);
>
> Will it copy all x behind the scenes in both cases?
Yes.
> If so, then I wish this to be more efficient so I should probably pass
> a reference right?


Yes.
> How can I do this in both cases?


For the first case, you can't unless you declare c as a reference to
vector<int> and initialize it with c.


It's not that you can't. The copy constructor for std::vector already
takes a non-modifiable reference to the object being copied. So,

c = x;

calls 'c's copy constructor with a const reference to 'x'.


Yes, and that will copy x to c. As I understood the OP, he wanted to get rid
of that copy. The only way to do that would be - as I mentioned - to make c
a reference to x instead of an own vector.
Anyway, it is very well possible that I misunderstood the OP here.
'x' is not copied to a temporary, as is the case with 'foo'; only the
value of 'x' is copied to 'c'. The call is already as efficient as it can
be.


That was actually my point.

Jul 23 '05 #5
da********@warp mail.net wrote:

[snip]
How can I do this in both cases?


For the first case, you can't unless you declare c as a reference to
vector<int> and initialize it with c.

It's not that you can't. The copy constructor for std::vector already
takes a non-modifiable reference to the object being copied. So,

c = x;

calls 'c's copy constructor with a const reference to 'x'. 'x' is not
copied to a temporary, as is the case with 'foo'; only the value of 'x'
is copied to 'c'. The call is already as efficient as it can be.

/david


I could not make any sense out of your post. 'c = x; ' exactly calls
vector's assignment operator. If you want to avoid this 'copy' you need
to do what Rolf Magnus had suggested in his previous post.

Can you please elaborate more (optionally with an example) to prove your
point?

Thanks
Krishanu
Jul 23 '05 #6


Krishanu Debnath wrote:
da********@warp mail.net wrote:

[snip]

How can I do this in both cases?

For the first case, you can't unless you declare c as a reference to
vector<int> and initialize it with c.

It's not that you can't. The copy constructor for std::vector already
takes a non-modifiable reference to the object being copied. So,

c = x;

calls 'c's copy constructor with a const reference to 'x'. 'x' is not
copied to a temporary, as is the case with 'foo'; only the value of 'x'
is copied to 'c'. The call is already as efficient as it can be.

/david


I could not make any sense out of your post. 'c = x; ' exactly calls
vector's assignment operator. If you want to avoid this 'copy' you need
to do what Rolf Magnus had suggested in his previous post.

Can you please elaborate more (optionally with an example) to prove your
point?


The question was:

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?

My point is, no, 'x' will not be copied in both cases. In the case of
'c = x', 'x' is passed by const reference, whereas in the case of
'foo(x)', 'x' is passed by value, and hence is copied (to a temporary).

Given the context, I do not think OP's question was about how to avoid
copying 'x' altogether. However, you are correct to point out my error:
it is the assignment operator that is called, not the copy constructor.
/david

Jul 23 '05 #7
da********@warp mail.net wrote:
[snip]


The question was:

What happens when I do:
c = x;

and
foo(x);

Will it copy all x behind the scenes in both cases?

My point is, no, 'x' will not be copied in both cases. In the case of
'c = x', 'x' is passed by const reference, whereas in the case of
'foo(x)', 'x' is passed by value, and hence is copied (to a temporary).


Makes much sense. Thanks for the clarification.

Krishanu

Jul 23 '05 #8
You could also templatize foo and pass iterators to the container,
rather than the container itself. Here's some psudocode to illustrate:

template<class iter> foo(iter itBegin, iter itEnd);

vector<int> c;
foo(c.begin(), c.end());

Take care,

John Dibling

Jul 23 '05 #9


John Dibling wrote:
You could also templatize foo and pass iterators to the container,
rather than the container itself. Here's some psudocode to illustrate:

template<class iter> foo(iter itBegin, iter itEnd);

vector<int> c;
foo(c.begin(), c.end());

Take care,

John Dibling


Thanks for the suggestion. Will that work for constructors?

Cheers,

Paulo Matos

Jul 23 '05 #10

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

Similar topics

10
15840
by: Michael Aramini | last post by:
I need to represent 1D and 2D arrays of numeric or bool types in a C++ program. The sizes of the arrays in my intended application are dynamic in the sense that they are not known at compile time, so I'd like to use an STL container class template such as valarray or vector to represent 1D arrays, and valarrays or vectors of valarrays or vectors to represent 2D arrays. As I said the sizes of the arrays in my intended application are...
5
3420
by: Pratyush | last post by:
Hi, Suppose there is a vector of objects of class A, i.e., std::vector<A> vec_A(N); The class A satisifies all the STL vector requirements. Now I wish to add some attributes for each of the objects in the vector vec_A. Suppose there are K attributes to be added. For each of the attributes I define K vectors of appropriate types. Say, the attributes have types type1, type2, ..., typeK. So I define std::vector<type1> attr1(vec_A.size());
5
2318
by: Computer Whizz | last post by:
I was reading through Accelerated C++ at work when I read through the first mention of Vectors, giving us certain functions etc. Is there any benefit of Arrays over Vectors? Since all Vectors seem to be (in my eyes at least) are glorified Arrays. - Now I know there's a bit more difference, but what exactly are the advantages of Arrays over Vectors (if any)? Oh, and please keep it in mind I am a real beginner in C++ but can
19
4381
by: chris | last post by:
Hello, I've recently been trying to understand the various structures supplied by c++, and the one I find most confusing is deque. One quick question about this. It seems most implementations of deque are quite complex. Why couldn't I implement deque with a couple of vectors V,W where the deque is the element of V in reverse order followed by W? This would appear to me to satisfy all the conditions, and be significantly simpler. Am I...
3
3247
by: Amit | last post by:
Hello. I am having some problem organizing a set of vectors. The vectors itself, could contain a pointer( say integer pointer) or could contain another object MyClass. 1>So, first of all, is there anyway where I can accomodate both the vector types into a single set. Something like a set<vector<void*>, my_compare func >. Right now, I am having them as two different set dayatypes.
4
2024
by: Dr. J.K. Becker | last post by:
Hi all, I have vectors that holds pointers to other vectors, like so: vector<whatever> x; vector<whatever*> z; z=&x; Now I add something to x
5
18254
by: madhu | last post by:
http://msdn2.microsoft.com/en-us/library/fs5a18ce(VS.80).aspx vector <intv1; v1.push_back( 10 ); //adds 10 to the tail v1.push_back( 20 ); //adds 20 to the tail cout << "The size of v1 is " << v1.size( ) << endl; v1.clear( ); //clears the vector I have a few questions:
2
8694
by: wuzertheloser | last post by:
Use the program skeleton below (starting with #include <stdio.h>) as the starting point for quiz4. Add the necessary code to the functions prob1() and prob2(), and add the other 2 functions, as described in the text below. You do not need to change anything in main(). In void prob1(void), take a double floating-point number x from the keyboard and compute the function f(x), which is defined by:
1
2067
by: Rob | last post by:
How would I do this? I want to be able to handle vectors of many different types of data and vectors that can contain any number of other vectors of data. Currently, I have a templated function that handles vectors of vectors of <typename T(which could be anything from int to vectors of something else). As well, I have specialized/overloaded functions to handle the single-level vectors of data (e.g. vector<string>). So the templated...
2
3402
by: joeme | last post by:
How would one using STL do the following tasks: 1) merge 2 sorted vectors with dupes, result shall be sorted 2) merge 2 sorted vectors without dupes, result shall be sorted 3) merge 2 unsorted vectors with dupes, result does not need to be sorted 4) merge 2 unsorted vectors without dupes, result does not need to be sorted
0
9686
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
10475
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...
0
10250
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
10026
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
9068
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...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4139
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
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
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.