C++ :: Smart Accessor Function For Multiple Data Containers?

Mar 14, 2012

Suppose I'm writing a program designed to simulate a large company. I'm interested in tracking each company employee by the location where they work. This company has perhaps a thousand different locations:

class Employee {
public:
AccessorFunction1(); // does something
AccessorFunction2(); // does something different
AccessorFunction3(); // does something completely different
protected:
// Some data

[code]....

Once employees are created and pointers to them are saved in the proper Location vector, I write an accessor function, OrganizeLocation(), designed to do a number of operations on a given vector. The problem is, I have maybe a thousand vectors. How do I call this function and specify which vector I want?

Currently, I'm using this clunky solution:

void Company::OrganizeLocation(int a){
switch(a) {
case 1: {
for(unsigned int i=0; i<LocationA.size(); i++) {
LocationA[i]->AccessorFunction1();
LocationA[i]->AccessorFunction2();
LocationA[i]->AccessorFunction3();

[code]....

The key point here is that whichever vector I choose to operate upon, I'll do the exact same procedure every time. I hate this solution because it results in very long and repetitive code not to mention its very error-prone when you re-editing all those "LocationA 's into "LocationB/C/D/etc."

void Company::OrganizeLocation( string $WhichOne$ ){
for(unsigned int i=0; i<LocationA.size(); i++) {
Location$WhichOne$[i]->AccessorFunction1();
Location$WhichOne$[i]->AccessorFunction2();
Location$WhichOne$[i]->AccessorFunction3();
}

Or, if it can't be done in C++, is there a better design approach? Ultimately I need the Company object to hold multiple vectors but use one compact accessor function to perform operations on just one of them.

View 5 Replies


ADVERTISEMENT

C++ :: Accessor Function Paradigm - Set Value

Dec 14, 2013

class foo {
int val;
public:
int val() const { return val; } // get val
int& val() { return val; } // modify val

[Code] ....

I've almost always done something like foo.setVal(20). Saw some code doing it the other way and I was intrigued. What's everyone's opinion on the former paradigm?

View 4 Replies View Related

C++ :: Using Smart Pointers To Sort And Relink Potentially Large Data Elements

Feb 20, 2014

I am trying to use smart pointers to sort and re-link potentially large data elements. I have defined a class in my code for smart pointers, as listed below:

template <typename T>
class sptr {
public:
sptr(T *_ptr=NULL) { ptr = _ptr; }

[Code] ....

The object I'm trying to sort is a singly-linked list containing class objects with personal records (i.e., names, phone numbers, etc.). The singly-linked list class has an iterator class within it, as listed below.

template <class T>
class slist {
private:
struct node {
node() { data=T(); next=NULL; }

[Code] .....

The following is my function within my list class for "sorting" using the smart pointers.

template <typename T>
void slist<T>::sort(){
vector< sptr<node> > Ap(N); // set up smart point array for list
//slist<T>::iterator iter = begin();
node *ptrtemp = head->next;

[Code] .....

I must have a bad smart pointer assignment somewhere because this code compiles, but when I run it, std::bad_alloc happens along with a core dump. Where am I leaking memory?

View 6 Replies View Related

C++ :: Create Function That Calculates Sum Between Two Containers

Jul 1, 2012

I need to create function Sum() that calculates sum between two containers. Code below work fine except function Sum between two containers...

How I should re - write my code that everything work fine.

Condition of exercise is : "Also create a Sum() function that calculates the sum between two iterators. The function then uses the template argument for the iterator type and accepts two iterators, the start- and end iterator"

1>------ Build started: Project: HP2_ex2_iter, Configuration: Debug Win32 ------
1> main.cpp
1>c:all myс++ha level 7solutionlevel 7 homework overview of the standard template libraryhp2_ex2_itermain.cpp(47): error C2275: 'C1' : illegal use of this type as an expression

[Code]...

View 5 Replies View Related

C++ :: Multiple Of CSV File Used As Input / Extracting Data To A Output File - Getline Function

Jun 4, 2013

I have written a C++ program I have multiple of CSV file used as input, which I open one at a time and close it after extracting data to a output file which is the only file.

I run getline(inFile,line);
outFile << line << endl;

I run this code, and only part of it is goes to the output file I got, also have spacing randomly to specific file and inconsistent

But when I slower the code, like system("Pause") in the loop, I can get extract what I want perfectly....

Is my program running to fast, why getline would be skipping part of what things I want?

View 11 Replies View Related

C++ :: Popping From STL Containers

Feb 21, 2014

I've been working on a project that involves storing pointers to dynamically allocated class objects in an STL list, but trying to run it something's going wrong.

list<Actor*>::iterator it;
for(it = m_actors.begin() ; it != m_actors.end() ; ++it)
{
delete *it;

[Code]....

But it seems like that has a memory leak. Does pop_front() just call the destructor for the object, or will it delete a dynamically allocated chunk of memory? If not, how can I do that deletion to avoid a memory leak?

View 4 Replies View Related

C++ :: Smart Pointers In A Vector

Aug 21, 2014

I am new to smart pointers and have a question.If you push a smart pointer onto a vector and then some where later pop it back off it will delete the memory right?

View 1 Replies View Related

C++ :: Arrays And Smart Pointers

Aug 3, 2014

I'm writing quite a large program that needs to work with very large arrays (up to 100 million integers). It is necessary that i can access every point of the array directly (without running through the array) and that I use as little memory as possible. I first wrote the program with pointers that point to allocated heap memory. It works fine but now I wanted to use smart pointers instead (so I'm sure to have no memory leaks). Here's a simple visualization of my problem:

#include <iostream>
#include <memory>
using namespace std;
unique_ptr<int[]> upArray;
int main() {
int nArrayLength = 10;

[Code] ....

There are 2 things that do not work how I would like the to:

1. It wants me to assign the heap memory in one step: unique_ptr<int[]> upArray(new int[nArrayLength]); But I'd like to have the unique_ptr in my Class_Declaration before I know the array length and allocate the memory later.
2. *(upArray + i) = i;
cout << *(upArray + i);

Those lines don't work! How else can I do it.

View 6 Replies View Related

C++ :: Dynamic Containers With Arrays?

Feb 14, 2015

Im trying to create a function that searches my array for a specific string, and then displays that string and the other content associated with it. I'm basically searching for a keyword within an array that has multiple strings with in each element.

View 4 Replies View Related

C++ :: How To Design A Smart Pointer Class

Nov 11, 2014

smart pointer class is the one that take in charge of release allocated resource when itself destroyed.

recently,i want design a smart pointer class, it take in charge of release resource allocated by new or new[].

my problem how to design destructor, you should determine the pointer ptr is pointer an array or a single object.

the structure of this smart point class may be:

template<class T>;
class smart_pointer{
public:
smart_pointer(T* p):ptr(p){};
~smart_pointer(){

[Code] ......

View 6 Replies View Related

C++ :: Pass By Reference To Smart Pointer?

Jul 30, 2014

I just want to know if there is any real difference between the two below, if yes, when would i use one over the other? I would thought the "&" is pointless in below function, as far as the data is concerned.., the only things is with "&", if the pointer address value is changed in Test function, it will affect the caller's copy of data. Both function should behave the same if data is changed.

Code:

Between

void Test(QSharedPointer<Data> data)
{
}

and

void Test(QSharedPointer<Data> & data)
{
}

View 6 Replies View Related

C++ :: Custom STL Compatible Containers And Iterators?

Jul 18, 2012

So i made an STL compatible container.And to make this work I had to make my own iterator (derived from std::iterator).

What is the portable (if any) and "well behaved" thing to do in case of usage anomalies.such as iterating an iterator too far, or passing an invalid index to a operator[]

Looking at how VC++ does things in something like std::array or std::vector.

Code:

iterator_type& operator+=(difference_type offset)
{// increment by integer
#if _ITERATOR_DEBUG_LEVEL == 2
if (size < index + offset)
{// report error

[Code] .....

lots of names starting with underscores, so it's implementation specific. Is there even a "well behaved" thing to do ? Or is any such work always going to be compiler specific?

View 2 Replies View Related

C++ :: Two Identical Storage Containers - Typecasting

Oct 27, 2012

I have a situation where I have two identical storage containers:

Code:
////////////// multiplatform version
union _SOVector3 {
struct { float x, y, z; };
struct { float r, g, b; };
float v[3];

[Code] .....

SOVector3 is part of a namespace with specialized functions that are generic and intended for multiplatform usage.

GLKVector3 is dedicated to the Mac and has its own set of functions.

But what I want to do is freely interchange the storage between these two namespaces. Such as like this:

Code:
start = clock();
SOVector4 myVec4 = SOVector4Make(1.0f, 3.0, 6.0f, 1.0);
SOMatrix4 myMat4 = SOMatrix4Identity;
for (uint i=0; i<100000; ++i ) {

[Code] ....

But I am getting errors when I typecast this.

View 1 Replies View Related

C++ :: Why Asterisk Required On Smart Pointers For Assigning Value

May 19, 2013

When i try to compile this code it gives me a error during run-time saying "*program name* has stopped working"

Code:
#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::unique_ptr;

[Code] .....

Why is this happening? Also why do you need the asterisk on smart pointers to assign them a value? Is it just because, or is there a reason.

View 5 Replies View Related

C++ :: Containers That Doesn't Change Member Address

Jun 25, 2013

#include <iostream>
#include <vector>
using namespace std;
int main() {
int * ptr;
vector<int> data;
data.resize( 1000 );

[Code] ....

So I need container that doesn't rellocate their address, It doesn't need to be like vector that everything is in a single pointer such as

int * a = new int[2000];

I have a pointer pointing to a member of a container and it needs to remain valid... doing

vector<int *> Array;
// allocating
for( int i = 0; i < 1000; ++ i ){

Code] ...

Waste of time, allocating them and deallocate them seem to take some time too

a List is also not efficient enough because I access them based on index

It is not a int it is pointing to but a texture, for the sake of simpler example I pick int

So is there a container that doesn't change member address and allocate when it needs to expand ?

View 3 Replies View Related

C++ :: Manipulating Set Of Containers - Vector Of Vectors Of Objects

Mar 5, 2013

I need manipulating a set of containers. I created a vector that contained vectors of objects:

std::vector< std::vector<Terrain> > mapArray(num1, std::vector<Terrain>(num2));

where num1 and num2 are arbitrary numbers. and Terrain is the class of objects I'm trying to store.

I want to be able to use push_back on both the main vector and the vectors within the mapArray vector but I'm unsure of how to target the inner vectors with push_back. How to dynamically store a 2D array of objects.

View 10 Replies View Related

C++ :: A Compiler Error With The Implementation Of Smart Pointer

Oct 8, 2014

Here is my code,

Code:
class A {
public:
void display() {
cout<<"A"<<endl;

[Code] .....

The compiler error is "error C2039: 'display' : is not a member of 'SP<T>'". What am I missing here?

View 14 Replies View Related

Visual C++ :: Creating Containers That Respond To User Actions?

Oct 16, 2013

I am looking for direction on what topic I should be reading up on. I am new to C++ and Windows MFC.

This is my real world problem, in the context of the application user. (these term do not refer to OPP concepts)

I want to create shapes (containers) in an application that will respond and collect other objects;

Imagine a Windows frame, containing several 2 dimensional squares. I want to be able to drag and drop marbles into the squares,and have the square retain and display the marbles in the square, in the order that they were dropped in.

How do I create the shapes, and how will the square sense when a marble is over it?

How would I create irregular shapes (a combination of lines and curves) that would be responsive to the marbles?

View 2 Replies View Related

C++ :: Map Storing Multiple Data Types

Jul 11, 2014

I am trying to create a generic map container which shell contain data of different datatypes. I already found a solution in this forum here:

[URL]...

Introducing a container with a Base Class as content type and inserting objectes of Derived Class types from that Base Class suites my implementation very well. But it is not really working. I implemented it this way:

class MyType {
public:
MyType() {}
virtual ~MyType() {}
}; template <class PT> class ParseType : public MyType

[Code]...

Then I insert one element.

// index being an object of type Parser<string>
ParseType<string>* test = new ParseType<string>( index );
// and index.val(0) = "-n"
iMap.insert( pair< string, MyType* >( index.id(0), test ) );

Now I think I should be able to call

const string key("-n");
iMap.at(key)->content->val(n);
Or
iMap.at(key)->get_val(n);

But neither one compiles with the error that "class MyType" (as the map container is pointing to a MyClass object) has no member/member function "content"/"get_val".

I also tried introducing member and member function "content" and "get_val" in "class MyType", which I thought should be hidden while constructing ParseType<string>. This would compile but it does not call the member "content or member function "get_val" from class ParseType.

A second try was to remove templatization of "class ParseType" and introduce a specific, let's say, "class ParseString" for objects of type Parser<string>. But the problems remain the same either the compiler complains due to missing member/member function or retreiving the map content will not call the derived class member/member function.

View 4 Replies View Related

C++ :: Accept Multiple Data Types

Jun 17, 2014

Basically I do not want to use a menu, instead just accept either an float or a single character. Then send the data to the appropriate spot based on the user input. I have been unable to convert the char to a float, and even if I did the char would probably only accept the first digit, say user enters '15' it would only read the '1'. I've tried strings instead of char but then unable to use the isalpha function. Do I need a char[] and then iterate through to get the numeric data? Then how do i make '1' and '5' become 15. There is probably a solution. I've also tried to use a loop waiting for the correct data while(!(cin >> letter)) which works but how do I get out if the user enters number.

#include <iostream>
#include <cctype>
#include <string>
#include <cstdlib>
using namespace std;

[code].....

View 3 Replies View Related

C++ :: Getting Multiple Ints From String Data

Feb 18, 2013

I'm having trouble making a .obj loader at present I'm trying to load faces that are defined as follows:

f 1/1/1 2/2/2/ 3/3/3

So far I've separated the the three number groupings into three strings, I've had a few issues with stringstreams and would like a simple solution.

View 1 Replies View Related

C++ :: How To Write Data Into Multiple / Different Files

May 7, 2013

I am new to c++ programming i just want to know how to write the data into different files.Suppose my input files has 1-8 ids so each id data must be stored into each different file. And below is my code.

#include<fstream>
#include<iostream>
#include <cstdlib>
#include <algorithm>
#include<list>
#include <math.h>
#include<conio.h>
#include<string>
#define PI 3.14159265
using namespace std;
double angle;
ifstream indata;
ofstream outfile;

[Code] .....

View 1 Replies View Related

C++ :: Smart Array Class - Constructor Throws Wrong Exception

Jan 24, 2014

Writing a smart array class for my C++ class. I'm running into a problem where the constructor apparently throws the wrong exception. Compiled on G++ with C++11 extensions enabled.

Code:
// headers
#include <iostream>
#include <utility>
#include <cctype>
// stuff we need from namespace std
using std::cout;
using std::cin;

[Code] .....

When I try to check the error-handling code, when I enter a size less then two, Array's ctor throws InvalidSize, and gets caught, all good. But when I enter a letter, the ctor also seems to throw InvalidSize!

View 14 Replies View Related

C :: Inputting Data From Multiple Lines Using Scanf?

Aug 1, 2013

How would I go about inputting data from multiple lines using scanf?

So far I have tried a loop and somehow checking for '' but can't seem to figure it out..

E.g I want to be able to scanf the ints below line by line and print them( if that makes sense) .

5 15 20 30 5 6
5 6 8 20 34
5 6 7
5 2
2 6 7 2 1 6

This is what i've tried so far, but am really lost!

Code:

int input;
while(scanf("%d", &input)){
printf("%d",input);
if(input == '
'){
continue;}}

View 13 Replies View Related

C++ :: Make A Table Class That Will Be Able To Have Multiple Columns Of Data?

Sep 17, 2014

I am trying to make a table class that will be able to have multiple columns of data. I want it to have something to hold data (I was using a 2D vector for only one data type) in it, somewhat like a pair, but for any number of data types. The class is a template to make it generalized.

I have looked a little at variadic templates, but I don't know how to declare the vectors for each data types then.

View 4 Replies View Related

C++ :: Multiple Data Streams In One Class - Handling All In One Member

Jan 24, 2014

I have to implemente the to_string method. Whats the fastest way? Stringstreams. But I have to use C++ without any headers, so I need to implement the stringstream class. How can an stringstream hold one float? An double? Hoq cqn I implement an strigstream myself?

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved