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

Home Posts Topics Members FAQ

returning a const vector

At least that is what I think I want to do.

What is the proper way for me to return multiple data member objects
from an accessor method in my class while ensuring the data does not
get changed, but allowing iteration through the data?

I tryed returning a const vector but the compiler does not like the
idea of my using an iterator to look through the vector down the
road...I assume because an iterator acts like a pointer and allows you
to change the data?

Thanks,
Christopher

Here is my class currently:

#include <direct.h>
#include <winsock2.h>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

//------------------------------------------
class Directory
{
public:

Directory(){}
~Directory(){}

// Accessors
string & GetPath()
{
return m_path;
}

vector<Director y> & GetSubdirectori es()
{
return m_subdirectorie s;
}

vector<string> & GetFilenames()
{
return m_filenames;
}

// Mutators

//--------------------------------
// Gather file and subdirectory info from the directory specified by
path
// Note: (recursive)
bool Set(const char * path)
{
// Make sure the path points to a valid directory
HANDLE file_handle = INVALID_HANDLE_ VALUE;
WIN32_FIND_DATA file_data;
DWORD error;

// Add the wild card character to the path to search it's
contents
string search_path(pat h);
search_path += "\\*";

// Search for the first file or directory in the path
file_handle = FindFirstFile(s earch_path.c_st r(), &file_data);

// Was the supplied path a valid directory? (there would at least
be a "." or ".." found)
if(file_handle == INVALID_HANDLE_ VALUE ||
!(file_data.dwF ileAttributes & FILE_ATTRIBUTE_ DIRECTORY) )
{
cout << path << "\n is an invalid directory. Error:" <<
GetLastError() <<endl;
FindClose(file_ handle);
return false;
}
else
{
// Set this directory object's path to the supplied path
m_path = path;

// Do the following until no more files or directories are
found
do
{
// Skip the . and .. directories
if( strcmp(file_dat a.cFileName,"." ) != 0 &&
strcmp(file_dat a.cFileName,".. ") != 0 )
{
// Check if we found a file or a directory
if(file_data.dw FileAttributes &
FILE_ATTRIBUTE_ DIRECTORY)
{
// Get the path to the subdirectory
Directory subdirectory;
string subdir_path(pat h);
subdir_path += "\\";
subdir_path += file_data.cFile Name;

// Read the subdirectory's contents
subdirectory.Se t(subdir_path.c _str());

// Insert the record
m_subdirectorie s.push_back(sub directory);
}

// Otherwise, we found a file
else
{
// Get the filename
string filename(file_d ata.cFileName);

// Insert the record
m_filenames.pus h_back(filename );
}
}
}while(FindNext File(file_handl e, &file_data) != 0);
}

// Release the file handle
FindClose(file_ handle);

return false;
}

private:

// Data
string m_path;
vector<Director y> m_subdirectorie s;
vector<string> m_filenames;
};

Jul 23 '05 #1
4 2403
<cp***@austin.r r.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com
At least that is what I think I want to do.

What is the proper way for me to return multiple data member objects
from an accessor method in my class while ensuring the data does not
get changed, but allowing iteration through the data?

I tryed returning a const vector but the compiler does not like the
idea of my using an iterator to look through the vector down the
road...I assume because an iterator acts like a pointer and allows you
to change the data?


Use const_iterator rather than iterator.
--
John Carson
Jul 23 '05 #2
I get this error mesage when trying to use a const_iterator

144 C:\Documents and Settings\pisz_c hris\My
Documents\proje cts\vidparser\m ain.cpp passing `const Directory' as
`this' argument of `const std::string& Directory::GetP ath()' discards
qualifiers

on this block

cout << "Subdirectories :\n";
for( vector<Director y>::const_itera tor it =
root_dir.GetSub directories().b egin(); it !=
root_dir.GetSub directories().e nd(); it++)
{
cout << it->GetPath() <<endl;
}

Jul 23 '05 #3
c...@austin.rr. com wrote:
At least that is what I think I want to do. [snip] vector<string> & GetFilenames()
{
return m_filenames;
}


I usually prefer to do this in a more STL-ish way. Something along the
lines of this psudocode:

template<class OutputIterator>
void Directory::GetF ilenames(Output Iterator itX)
const
{
std::copy(m_fil enames.begin(), m_filenames.end (), itX);
}

There are some benefits to this approach, I think. For one thing, the
signature of GetFilenames() isn't dependant on Directory's
implementation details. Therefore, clients of Diretory also aren't
dependant on Directory's implementation details -- at least,
GetFilenames() isn't a culprit here. In this case, you could change
the type of m_filenames from vector to list for example, and the
signature of GetFilenames() still needn't change.

For another, GetFilenames() imposes fewer restrictions on clients than
if it returned some sort of reference to a container. 'itX' can be
anything that is valid as an OutputIterator. It could be a
back_insert_ite rator, or even just a pointer to a fixed-size C-style
array. The choice is on the client.

For yet another, this method is very easy to extend. Consider if you
chose to extend your method by adding an optional paramater that
specified wildcards. Then your function could retuyrn only those
filenames that pattern-match the wildcard. If the method is
implemented as I have above, it could simply be extended by using
'copy_if()'* instead of 'copy()'. If you implement it by returning a
reference to a vector or something like that, it might be impossible or
at least very difficult to implement.

This is also a very easy method to implement. I find that when a piece
of code is harder to write than it seems like it should be, its very
often becasue my design is wrong -- I'm trying to write a bad piece of
code. If the design is 'right', the code can practically write itself.

Take care,

John Dibling

* : regarding copy_if(). There isn't one as defined in the Standard,
but this is a very easy and useful thing to implement. See Scott
Meyers' "Effective STL" item # 36 for one implementation, or "Extending
the STL" in the February 2005 C/C++ User's Journal for another.

Jul 23 '05 #4
cp***@austin.rr .com wrote:
I get this error mesage when trying to use a const_iterator

144 C:\Documents and Settings\pisz_c hris\My
Documents\proje cts\vidparser\m ain.cpp passing `const Directory' as
`this' argument of `const std::string& Directory::GetP ath()' discards
qualifiers

on this block

cout << "Subdirectories :\n";
for( vector<Director y>::const_itera tor it =
root_dir.GetSub directories().b egin(); it !=
root_dir.GetSub directories().e nd(); it++)
{
cout << it->GetPath() <<endl;
}


// Accessors
const string & GetPath()const
{
return m_path;
}

one can call only const methods on a const object

Jul 23 '05 #5

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

Similar topics

4
1780
by: Patrick | last post by:
I want to achieve the following behaviour but I am having trouble getting there...bare with me im knew to c++ , so its probably rather trivial! To have a class ClassA, and composed within this class is an instance of another class, ClassB. I want to have a method getClassB that returns a reference to the instance of ClassB composed within ClassA. So when a client calls getClassB they are supplied with a reference to the instance of...
18
2147
by: cppaddict | last post by:
Hi, Is it considered bad form to have the subscript operator return a const reference variable? If not, what is the proper way to do it? My question was prompted by the code below, my problematic attempt to implement a subscript operator that returns a const reference. The dubious code is marked at the end. <code>
8
2090
by: Derek | last post by:
Some authors advocate returning const objects: const Point operator+(const Point&, const Point&); ^^^^^ Returning a const object prevents some bad code from compiling: Point a, b, c; (a + b) = c; // error
5
2278
by: Alfonso Morra | last post by:
Hi, What is the recomended way of returning an STL container (e.g. std::string, std::vector etc fom a function? Is it by simply returning a local variable? (I doubt it) std::string foo(const std::string& rhs) { std::string var = rhs ; var += " received" ;
1
1419
by: maadhuu | last post by:
what is the use of returning "const & "from a function in C++ ?? Is it used somewhere at all ?? thank you, Ranjan.
8
1750
by: Richard | last post by:
what is the syntax for returning a vector? temp is a vector return temp; ? return temp<>; ? return temp<int>; ?
10
1869
by: andrew browning | last post by:
i have overlaoded all of my arithmetic operators but all are functioning as multiplication. below is a sample of the addition operator: Rational operator + (const Rational& r1, const Rational& r2){ //Postcondition: sum of r1 and r2 are returned int numerator; int denominator;
2
1629
by: =?iso-8859-9?B?RGlu52F5IEFr5/ZyZW4=?= | last post by:
Following function void mdelr(int *ar1, int a, int b, int d ) { int i,j,tmp; int *temp; for (i=0; i<a; i++) {
23
2945
by: pauldepstein | last post by:
Below is posted from a link for Stanford students in computer science. QUOTE BEGINS HERE Because of the risk of misuse, some experts recommend never returning a reference from a function or method. QUOTE ENDS HERE I have never heard anyone else say that it is a problem for a function
0
9543
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
10488
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
10237
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
9077
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
7567
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
5588
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4144
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
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.