473,782 Members | 2,437 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Scope of std::vector

I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.

In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];

Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access the
contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such an
object so that it can be accessed from anywhere within the class?
Oct 14 '05 #1
13 2357
Steve wrote:
Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access the
contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such an
object so that it can be accessed from anywhere within the class?


There's nothing wrong with this as long as you FillVector before you
getSecondBanana . Post the code and we'll help you out further.

Jacques.
Oct 14 '05 #2

"Steve" <st***@hello.co m> wrote in message news:43******** **@x-privat.org...
I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.

In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];

Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access
the contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such
an object so that it can be accessed from anywhere within the class?

Could you please post some code that demonstates your problem? Please
remember to keep it minimal and compile-able:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
Regards,
Sumit.
--
Sumit Rajan <su*********@gm ail.com>
Oct 14 '05 #3

"Steve" <st***@hello.co m> wrote in message news:43******** **@x-privat.org...
I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.

In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];

Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access
the contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such
an object so that it can be accessed from anywhere within the class?

Could you please post some code that demonstates your problem? Please
remember to keep it minimal and compile-able:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8
Regards,
Sumit.
--
Sumit Rajan <su*********@gm ail.com>

Oct 14 '05 #4
Steve wrote:

I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.

In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];

Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access the
contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such an
object so that it can be accessed from anywhere within the class?


Your analysis is wrong.
The only thing I can conclude from what you wrote, is:
You may have passed the vector the wrong way: pass per
value instead of pass per reference.

An analogy. In ...

void foo( int i )
{
i = 5;
}

int main()
{
int j = 3;
foo( j );
/// <- Here j still has the value 3, since a copy of j is
/// passed *per value* to foo.
}

.... why does j still have the value 3, when foo attempted to change it
to 5. The answer is: because j is passed per value, a copy of it is passed
to foo. You can change that copy inside foo as often as you like in foo,
that will not impress j.

On the other hand:

void foo( int& i )
{
i = 5;
}
int main()
{
int j = 3;
foo( j );
/// <- Here j has the new value of 5, since it is passed per reference to foo.
/// foo creates a new name for j, inside foo j is known as i. Whatever happens
/// to i, happens to j, since j and i are the same variable.
}

If this is not what you did wrong, then post your code.

--
Karl Heinz Buchegger
kb******@gascad .at
Oct 14 '05 #5
"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:3r******** ****@individual .net...

Could you please post some code that demonstates your problem? Please
remember to keep it minimal and compile-able:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8


OK, I'll post the code when I get home (I don't have access to it here).
Oct 14 '05 #6

Karl Heinz Buchegger wrote:
Steve wrote:

I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.

In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];

Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access the
contents of this. This suggests to me that the scope of the vector is
restricted to the method it is filled in. How do I set the scope of such an
object so that it can be accessed from anywhere within the class?


Your analysis is wrong.
The only thing I can conclude from what you wrote, is:
You may have passed the vector the wrong way: pass per
value instead of pass per reference.

....

Well it is also possible that there are simply two different vectors
both named bananas. As usual, having the source would probably help
shed more light on the matter.

Also, could we have a ruling on the legality of "Banana" and "bananas"
as legal C++ identifiers? Based on my knowledge acquired from this
newsgroup, I believe that the only legally recognized identifiers
permitted in a well-formed C++ program are "foo" and "bar".

Greg

Oct 14 '05 #7
"Steve" <st***@hello.co m> wrote in message news:43******** **@x-privat.org...
I have defined the following private object:

std::vector<Ban ana> bananas;

in my header file. I have also added a method called FillVector(), which
sets the size of the vector and fills it with Banana objects.
You don't show how you're filling the vector. One sure way is

bananas.push_ba ck(my_banana);
bananas.push_ba ck(your_banana) ;
// etc.
In another method (getSecondBanan a()) I want to access the contents of
bananas, using e.g.

Banana second_banana;
second_banana = bananas[1];
You are not accessing the contents of bananas. You are taking a copy of the
second element.
Unfortunately my program crashes when I try to do it like this. However it
*does* work when I fill the vector in the same method as I try to access
the contents of this.
We can only guess: Does Banana need and provide copy constructor, operator=,
and destructor?
This suggests to me that the scope of the vector is restricted to the
method it is filled in.
You don't show but I think bananas is a member of a class. In that case,
bananas will be alive as long as the encapsulating object is alive.
How do I set the scope of such an object so that it can be accessed from
anywhere within the class?


It already happens. You have a bug somewhere else.

Ali

Oct 14 '05 #8

Greg wrote in message
<11************ *********@g47g2 000cwa.googlegr oups.com>...

Also, could we have a ruling on the legality of "Banana" and "bananas"
as legal C++ identifiers? Based on my knowledge acquired from this
newsgroup, I believe that the only legally recognized identifiers
permitted in a well-formed C++ program are "foo" and "bar".
Greg


You are trying to compare apples to oranges!
[ you also forgot 'widgets'. ]

--
Bob '<G>' R
POVrookie
Oct 14 '05 #9
"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:3r******** ****@individual .net...

Could you please post some code that demonstates your problem? Please
remember to keep it minimal and compile-able:
http://www.parashift.com/c++-faq-lit...t.html#faq-5.8


I get error Unhandled exception at 0x00415329 in ClientTestClass es.exe:
0xC0000005: Access violation reading location 0x000002c4. It's something to
do with the way I'm filling and/or accessing the vector.

I need to get RequestCall() to return a call from the call_list vector.

/* Manager.cpp */

void Manager::Login( )
{
proxy.FillVecto rs(); /* fills the vector in ClientProxy */
proxy.RequestCa ll(current_camp aign); /* crash occurs in this method */
}

/* ClientProxy.h */
#ifndef __CLIENTPROXY__
#define __CLIENTPROXY__
#include "Call.h"
#include "Campaign.h "
#include "User.h"
#include "vector"
using namespace std;
class ClientProxy

{

public:
ClientProxy();
User Login(const std::string& sname, const std::string& ip, int pn);
Campaign RequestCampaign s(User u);
Call RequestCall(Cam paign c);
bool MarshallRequest ();

void FillVectors();

private:
/* Test variables below */
Call GetNextCall();
int call_counter;

/* Real vars */
Call current_call;
Campaign current_campaig n;
User user;
vector<Campaign > campaigns;
vector<Call> call_list;
};
/* END CLASS DEFINITION ClientProxy */

#endif

/* ClientProxy.cpp */

#include "ClientProx y.h"
#include "Call.h"
#include <vector>

ClientProxy::Cl ientProxy()
{

}

void ClientProxy::Fi llVectors()
{
printf("\n-FillVectors()") ;
vector<Campaign > campaigns(5);
campaigns[0] = Campaign(1, "Camp1");
campaigns[1] = Campaign(2, "Camp2");
campaigns[2] = Campaign(3, "Camp3");
campaigns[3] = Campaign(4, "Camp4");
campaigns[4] = Campaign(5, "Camp5");

vector<Call> call_list(5);
call_list[0] = Call(1,"0121575 5533","","Dave Jones","Jones
Construction"," 123 Main Street","",""," ");
call_list[1] = Call(2,"0121573 1432","","Steve Martin","Martin s
Butchers","10 West Street","",""," ");
call_list[2] = Call(3,"0131543 5467","","Phil Babb","BB Insurance","3 North
Street","",""," ");
call_list[3] = Call(4,"0141577 2234","","Tony Van Bronkel","GVK", "12 South
Street","",""," ");
call_list[4] = Call(5,"0151812 6534","","Steve Alabaster","MRM ","13 High
Street","",""," ");
call_counter = 0;

//printf(call_lis t[0].GetName().c_st r());
}

User ClientProxy::Lo gin(const std::string& sname, const std::string& ip, int
pn)
{
user.SetName(sn ame);
user.SetUserID( 1);
//call_list.inser t(sname);
return user;
}

Campaign ClientProxy::Re questCampaigns( User u)
{
return current_campaig n;
}

Call ClientProxy::Re questCall(Campa ign c)
{
//current_call = GetNextCall();

current_call = call_list[3]; /* ERROR BREAKS HERE */
printf("\n");
printf("-ClientProxy.Req uestCall()");
printf(current_ call.GetName(). c_str());
printf("-eof");
return current_call;
}

/* This is a temporary method to retrieve the contents of the call_list
vector */
Call ClientProxy::Ge tNextCall() {
Call ctemp = call_list[call_counter];
call_counter++;
return ctemp;
}

bool ClientProxy::Ma rshallRequest()
{
return 1;
}
Oct 15 '05 #10

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

Similar topics

27
5974
by: Jason Heyes | last post by:
To my understanding, std::vector does not use reference counting to avoid the overhead of copying and initialisation. Where can I get a reference counted implementation of std::vector? Thanks.
18
2879
by: Janina Kramer | last post by:
hi ng, i'm working on a multiplayer game for a variable number of players and on the client side, i'm using a std::vector<CPlayer> to store informatik about the players. CPlayer is a class that contains another std::vector<CPosition>. Because one of the players is the client itself (and the size of the vector<CPlayer> doesn't change during a game), i thought i could store a std::vector<CPlayer>::iterator "localplayer" that points to the...
20
17835
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; std::vector<double>::size_type size = src.size(); dest.reserve(size); for (std::vector<int>::size_type i = 0;
17
3361
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling this uovec at the moment (for Unit-Offset VECtor). I want the class to respond correctly to all usage of STL containers and algorithms so that it is a transparent replacement for std:vector. The options seems to be:
8
5115
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...
32
69696
by: zl2k | last post by:
hi, c++ user Suppose I constructed a large array and put it in the std::vector in a function and now I want to return it back to where the function is called. I can do like this: std::vector<int> fun(){ //build the vector v; return v; }
56
5820
by: Peter Olcott | last post by:
I am trying to refer to the same std::vector in a class by two different names, I tried a union, and I tried a reference, I can't seem to get the syntax right. Can anyone please help? Thanks
9
8897
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; Any ideas why is tihs happening? The code is as follows: template <class T> struct StdVectorStorage { std::vector<T>* _storage;
13
2963
by: jubelbrus | last post by:
Hi I'm trying to do the following. #include <vector> #include <boost/thread/mutex.hpp> #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple.hpp> class {
0
9639
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
10146
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...
1
10080
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
9942
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
8967
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
7492
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
6733
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3639
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2874
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.