Track/Display Array Index As Part Of Cout (C++) - c++

I have a command line C++ program that lets you enter basic information about a person (ID number, name, age, etc.) and I want to output to a console in the following manner:
-------------------------------------------------------------------
Index ID # First Name Last Name Age
-------------------------------------------------------------------
0 1234 John Smith 25
The person objects are stored in an array of Persons and I've overload the ostream (<<) operator to print out all of the fields like you see. The dashed lines and header come from a displayHdg() function. Anyhow, I have not been able to figure out how to get the proper index value for the array. Ideally, I'd like to generate the indices for each line, but all my attempts have failed. The array is looped through and each object printed in the main() function, and the ostream is overloaded in a person class, so I tried to use global variables as well as static variables, and all of those produce incorrect numbering (i.e. show 0, 1 the first time (for 2 objects), then change to 1, 2 on the next display). Any ideas?

Wouldn't this work? (formatting of ID field ommitted)
vector<Person> v;
for (int i = 0; i < v.size(); ++i)
cout << i + 1 << v[i] << endl;
This starts indexing at 1.

EDIT:
OK now I see what you want. You want to find an element in the vector!
std::vector<person>::iterator p =
std::find(Persons.begin(), Persons.end(), element);
if( p != Persons.end() )
{
std::cout << "index of element is: " << p-Persons.begin();
}
If you have the correct formating, you should be able to do the following:
for(size_t i = 0; i < Persons.size(); ++i)
{
cout << i << '\t' << Persons[i] << endl;
}
I would recommend taking a look at the formatting facilities in brief in this post. Using setw, left, right... manipulators is better than doing it manually.

You need to use "find" algorithms to find exact index of Person object in vector < Person>.

You could use wrapper class to hold index and print it according to your formatting in operator<<:
// wrapper to hold index
template<typename T>
struct Ti
{
Ti( size_t index, const T& t ) : index(index), val(t) {}
size_t index;
const T& val;
};
// you class
struct X
{
friend ostream& operator<<( ostream& out, Ti<X>& t );
protected:
int some_data;
};
// operator<< for X
ostream& operator<<( ostream& out, Ti<X>& t )
{
out << "test " << t.index << " " << t.val.some_data;
return out;
}
int main()
{
vector<X> xxx;
for ( size_t i =0; i < xxx.size(); ++i)
cout << Ti<X>(i+1, xxx[i]) << endl;
}

Related

Clear a class within a method

I want a function of the class that I have to clear the class before it applies its function without having to manually do it every time I ask the function of that class in a loop using the default constructor (as I do now).
An example
class Hello
{
public:
std::vector<int> a,b,c; //,d,e,... etc...
void set ( int value )
{
a.push_back(value);
b.push_back(value);
c.push_back(value);
//d.push_back...
//e.push_back...
//etc...
return;
}
};
std::ostream& operator<<(std::ostream& os, const Hello &hello)
{
for ( int i=0; i<hello.a.size(); i++ )
{
os << hello.a[i] << "\t";
os << hello.b[i] << "\t";
os << hello.c[i] << "\t";
//etc...
os << std::endl;
}
os << std::endl;
return os;
}
Somewhere in main
Hello hello;
for ( int i=0; i<5; i++ )
{
hello = Hello(); //want to get rid of this line and move its functionality to the set function
hello.set(i);
std::cout << hello << std::endl;
}
This will produce the correct result, however if I remove the line that clears the variable ( hello = Hello() ) then the set function will keep on appending to the vector and not clear the vector before it appends to it.
So basically I want to not worry about having to type the line hello = Hello(), every time I loop over the set function. By incorporating this clearing of the variable inside the set function of the class itself.
Typing a.clear(), b.clear() etc... before the push_back functions could work but with many vectors that would be a lot of lines. I was looking for a more elegant solution.

c++ creating an array of object in a function need to use the array in global scope

Hello I'm trying to implement a Extendible Hashtable.
My Problem is: I have an add function where i decide when to splitt a bucket and if i splitt it how many new buckets i need. So i create after an if statment an array of objects. So far no problems, now i want to print the array in a other function called:
std::ostream& print(std::ostream& o)
this is a function which is overloading the << operator as you can see in the Headerfile Container:
virtual std::ostream& print(std::ostream& o) const = 0;
inline std::ostream& operator<<(std::ostream& o, const Container<E>& c) { return c.print(o); }
So now my add function follows:
template <typename E>
void ExHashing<E>::add(const E e[], size_t len) {
if(isfirstBucket(head)){
fill_first_bucket(head, last, e,len,bucket);
}
else {
int number = 2;
Bucket<E> buckets = new Bucket<E>(number);
Bucket<E>* bucket_Pointer = buckets[1];
bucket_Pointer->Set_local_depth(1);
}
}
You can see that i make an array of Bucket objects which is working fine i can just not print them out in my print function because buckets is not defined there. My Print function:
template <typename E>
std::ostream& ExHashing<E>::print(std::ostream& o) const {
size_t number_of_buckets = (1 << global_depth);
for (size_t i = 0; i < number_of_buckets; ++i) {
o << "Bucket size = " << buckets->bucket_size; << " " << "Bucket index = " << buckets[i]->index << " " << "Global depth = " << global_depth << " " << "Local depth = " << buckets[i]->local_depth << "\n";
for (size_t j = 0; j < buckets[i]->bucket_size; ++j) {
o << " Bucket value " << "[" << j << "]" << " = " << buckets[i]->displayValues(j)<<"\n";
}
}
return o;
}
So how do give my print function acces to the array buckets? I can't add a parameter to function print since i just receives the comad print from the shell an should show my data in the buckets. Where do i initialise my array? I can't do it in the Constructor since i don't know how many data someone is going to put in i have to do inside the programm.
Containers store the necessary entry points to the held data as members of the object. In your case, you'd store the pointer to the buckets (and any other administrative data you'll need):
template <typename E>
class ExHashing {
Bucket<E>* buckets;
public:
ExHashing(): buckets(0) {} // Make sure the pointer is initialized.
ExHashing(ExHashing const&); // You'll likely need a copy ctor,
~ExHashing(); // a destructor,
ExHashing& operator= (ExHashing const&); // and copy assignment.
// as well as other mmebers
};
When you create or access your buckets you'd use this->buckets instead of a local variable.

how to overload << operator to output a vector that is a member of a class

I'm trying to use the << operator to output vectors that are private members of my class.
The compiler won't let me access the vectors directly as they are private, but it also won't let me access public member functions that return the vectors.
How do I make the << operator output all the contents of a private member vector?
This is my class:
class Name_pairs
{
public:
Name_pairs (){}
//....
vector<string> Names (){return names; }
vector<double> Ages (){return ages; }
vector<double> Sorted_ages (){return sorted_ages;}
private:
//....
vector<string> names;
vector<double> ages;
vector<double> sorted_ages;
};
This is the overloaded << function:
ostream& operator<<(ostream& os, const Name_pairs & n)
{
return os<< n.Names(); //won't let me access
return os<< n.names.size(); //won't let me access
}
This is the print function that I'm trying to replace by overloading the << function:
void Name_pairs:: print_name_age ()
{
cout << endl << endl;
cout << "These names and ages are now sorted" << endl;
for(int index = 0; index < names.size(); ++index)
{
cout << "index " << index << ": " << names[index]<< " is age: " << sorted_ages[index] <<endl;
}
}
n.Names() returns a vector and you can't print vectors directly through a standard operator << method. You have to iterate through the vector and print its elements.
std::ostream& operator<<(std::ostream& os, const Name_pairs& n)
{
if (!os.good())
return os;
auto names = n.Names();
std::copy(names.begin(), names.end(),
std::ostream_iterator<std::string>(os));
return os;
}
The line
return os<< n.Names(); //won't let me access
doesn't work, because you're trying to write a whole vector at once, instead of it's elements, and ostream doesn't provide an overloaded operator << for the std::vector. The solution is just writing elements from the vector, that's being returned by this function.
for(int i=0;i<n.Names().size();i++)
cout << n.Names()[i];
As a side note: you probably don't want to use your version with large vectors, since (unless your compiler is smart enough to make the function inline), will consume a lot of time to return the whole vector. Try returning a const reference to the vector, instead of the vector itself.

c++ overload pointer ostream

I am a learning c++ and have a class project due in 5 days. I've spent 4 hours researching how to do this however I have not come up with an answer yet. Save me stack!
Problem. I have a pointer to a class which holds a dynamic array. I need to take that array and save it to a file to retrieve later. Here are my 2 headers and the implementation. I am not writing the code to "save to file" yet as that will be easy once I get around this issue. My problem is it keeps printing the address of the pointer and not the data within.
vehReg.h
class vehReg {
public:
/* STUFF */
};
}
#endif
vehData.h
#include "vehReg.h"
using namespace std;
class vehData {
public:
//CONSTRUCTORS
vehData();
//DECONSTRUCTOR
~vehData();
//METHODS
friend ostream &operator<<( ostream &output, const vehData &v);
private:
typedef unsigned long longType;
typedef std::size_t sizeType;
sizeType used,capacity;
vehReg *data;
};
}
#endif
vehData.cpp
//CONSTRUCTOR
vehData::vehData(){
capacity = 5;
used = 0;
data = new vehReg[capacity];
}
//DECONSTRUCTOR
vehData::~vehData(){
delete []data;
}
/* TRYING TO ACCOMPLISH THIS WITH AN OSTREAM OVERLOAD */
void vehData::saveDataSloppy(){
ofstream myFile;
myFile.open ("database.db");
for(int i=0;i<used;i++){
myFile << data[i].getOwnerName() << "|";
myFile << data[i].getVehicleLicense() << "|";
myFile << data[i].getVehicleMake() << "|";
myFile << data[i].getVehicleModel() << "|";
myFile << data[i].getVehicleYear() << "\n";
}
myFile.close();
}
void vehData::saveData(){
cout << data;
}
ostream &operator<<(ostream &stream, const vehData &v){
stream << v.data;
}
}
v.data is a pointer, so it prints a pointer. How do you want it to
print whatever the pointer points to. With the exception of character
pointers, the << always prints what you give it (formatted in some
way). If you don't want it to print a pointer, give is something else.
Suppose it did dereference the pointer. What should it print: one
vehReg? 20? A pointer has no information concerning the size. If
you'd used std::vector<vehReg> (a much better choice), it would know
the size, but there's still no overload on std::vector, since the
system still doesn't know how you want it formatted (comma separated?
each on a new line?). And you've not told it how to print a vehReg
either.
You apparently understand the idea of how to overload <<. The first
thing you'll have to do is provide an overload for vehReg as well.
And both overloads must be defined in terms of existing overloads:
there's not one for std::vector, and the one for pointer doesn't do
what you want (and couldn't), so you'll have to loop in your << for
vehData and output each element, with whatever separators you decide
on. (If it's each element on its own line, then you can use std::copy
and an ostream_iterator for the loop, but this may be a bit in advance
of what you've learnt so far.) And forward to the << for vehReg for
each vehReg.
v.data is a pointer so it's a memory address.
*v.data is what the pointer is pointing to (which in this case is an integer).
For example,
#include <iostream>
using namespace std;
void main () {
int *ptr;
int var = 5;
ptr = &var;
cout << ptr << endl;
cout << *ptr << endl;
system("pause");
}
First line will print out something like: 0043F930
Second line will print out: 5
This should print out the elements held in the data array.
void vehData::showStructure() const {
for (int i = 0; i < capacity: i++) {
cout << data[i];
}
cout << endl;
}

Split array string in c++

I am new to cpp and have a situation in which I want to split array string
I have
for( i = k = 0; i < points[1].size(); i++ )
{
cout << points[1][k];
}
Output >>
[390.826, 69.2596]
[500.324, 92.9649]
[475.391, 132.093]
[5.60519e-44, 4.62428e-44]
I want
390.826
69.2596
500.324
92.9649
475.391
132.093
5.60519e-44
4.62428e-44
Please help me.Thanks
Assuming the type of point has public members x and y:
for( i = k = 0; i < points[1].size(); i++ )
{
cout << points[1][k].x << endl;
cout << points[1][k].y << endl;
}
If the members are something else, say, X and Y (the uppercase), then use the uppercase instead (or whatever it is).
The reason why you code prints the output that way, because operator<< has been overloaded for the type of the point. Something like:
std::ostream & operator<<(std::ostream & out, const point &p)
{
return out << "[" << p.x << "," << p.y << "]\n";
}
If you can search the above definition (or something similar) somewhere in your project source code, and then can change that to this:
std::ostream & operator<<(std::ostream & out, const point &p)
{
return out << p.x << "\n" << p.y << "\n";
}
then you wouldn't need to change the code in your for loop.
This has nothing to do with string splitting, what does points[1][k] actually return (i.e. it's type). Then look at how it has implemented the stream out operator (operator<<), and you'll see how the above is printed. This should give you a clue about the two individual values (i.e. fields of that *type), and you can simply access them and print them out.