473,791 Members | 3,074 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
13 2358

"Steve" <st***@hello.co m> wrote in message
news:kv******** ********@newsfe 3-gui.ntli.net...
"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 */
}

The code is not complete, compile-able or minimal. :-)

However, take a look at the comments below and let me know if it fixes your
problem.

/* ClientProxy.h */
#ifndef __CLIENTPROXY__
#define __CLIENTPROXY__
#include "Call.h"
#include "Campaign.h "
#include "User.h"
#include "vector"
using namespace std;
Not a great idea to have a using directive in a header file.

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;
Okay... two interesting members: call_list and campaigns.
};
/* 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);
Now you're defining another vector called "campaigns" . Remember that this is
a local one -- only valid here within this function.

//Consider skipping the above line and using vector<>::reser ve(). Something
like:
//campaigns.reser ve(5);

//Alternatively, you could initialize the vector to the size you want in the
initializer list
//for ClientProxy().
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");
And you make changes to your local "campaigns" . None of all this affects the
data member by the same name.

vector<Call> call_list(5);


Same problem here. We got a local "call_list" and changes made are only to
the local "call_list" .

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Oct 15 '05 #11

"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:3r******** ****@individual .net...

"Steve" <st***@hello.co m> wrote in message
news:kv******** ********@newsfe 3-gui.ntli.net...
"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 */
}

The code is not complete, compile-able or minimal. :-)

However, take a look at the comments below and let me know if it fixes
your problem.

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


Not a great idea to have a using directive in a header file.

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;


Okay... two interesting members: call_list and campaigns.
};
/* 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);


Now you're defining another vector called "campaigns" . Remember that this
is a local one -- only valid here within this function.

//Consider skipping the above line and using vector<>::reser ve().
Something like:
//campaigns.reser ve(5);

//Alternatively, you could initialize the vector to the size you want in
the initializer list
//for ClientProxy().


Or you could skip the above line (vector<Campaig n> campaigns(5);)
entirely and just use
campaigns.push_ back(...);
every time you want to add an element to the vector.

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hc ltech.com>
Oct 15 '05 #12
"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:3r******** ****@individual .net...

Or you could skip the above line (vector<Campaig n> campaigns(5);)
entirely and just use
campaigns.push_ back(...);
every time you want to add an element to the vector.


Thanks Sumit, it works a treat. :)
Oct 15 '05 #13
"Steve" <st***@hello.co m> wrote in message
news:kv******** ********@newsfe 3-gui.ntli.net...
"Sumit Rajan" <su*********@gm ail.com> wrote in message
news:3r******** ****@individual .net... /* ClientProxy.h */ #ifndef __CLIENTPROXY__
#define __CLIENTPROXY__
__CLIENTPROXY__ is a reserved name. Quoting from the standard with my
formatting:

<quote>
17.4.3.1.2 Global names

1 Certain sets of names and function signatures are always reserved to the
implementation:

-- Each name that contains a double underscore (_ _) or begins with an
underscore followed by an uppercase letter (2.11) is reserved to the
implementation for any use.

-- Each name that begins with an underscore is reserved to the
implementation for use as a name in the global namespace.165)

[...]

Footnote 165) Such names are also reserved in namespace ::std (17.4.3.1).
</quote>

[...]

Also, you included "vector" in ClientProxy.h:
#include "vector"
[...]
/* ClientProxy.cpp */

#include "ClientProx y.h"
#include "Call.h"
Then you included <vector> in ClientProxy.cpp
#include <vector>


Though I doubt that it has anything to do with your problems, those two
headers are potentially different, because the rules for finding headers
(e.g. searching in directory paths) are different between "" and <> headers.

Ali

Oct 17 '05 #14

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

Similar topics

27
5982
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
2881
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
17838
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
69698
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
5822
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
2965
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
9669
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
10428
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
10207
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
10156
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,...
1
7537
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
6776
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();...
0
5435
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
5559
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2916
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.