C++ - error: 'function' was not declared in this scope - c++

I have the following Problem:
error: 'kleiner' was not declared in this scope
My Professor told me, that my code just works fine for him.
The directories are all included in bulid options (I am using Code::Blocks).
Can someone please tell me what the problem might be?
main.cpp
#include <iostream>
#include "vector.h"
using namespace std;
int main(int argc, char *argv[])
{
Vector v1;
cout << "v1: " << v1 << endl;
Vector v2(8);
cout << "v2: " << v2 << endl;
cout << "Minimum von v2: " << v2.min() << endl;
Vector v3(v2);
cout << "v3: " << v3 << endl;
cout << "Anzahl von v3: " << v3.getAnzahl() << endl;
if ( kleiner( v3[2], v2[5] ) )//<<--<<--<<-- HERE IS THE PROBLEM
cout << v3[2] << " ist kleiner als " << v2[5] << endl;
int arr[5] = { 10, 5, 2, 3, 12 };
Vector v4;
cout << "v4: " << v4 << endl;
v4.setVector( arr, 4 );
cout << "v4 nach set: " << v4 << endl;
cout << "Minimum von v4: " << v4.min() << endl;
cout << "Anzahl von v4: " << v4.getAnzahl() << endl;
return 0;
}
vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include <iostream>
using namespace std;
class Vector
{
int* v;
int anzahl;
public:
Vector(int anzahl = 10);
Vector( const Vector& vec ); // Kopierkonstruktor
~Vector();
friend bool kleiner( const int& a, const int& b );
int min() const;
int getAnzahl() const;
int operator[]( const int i ) const;
void setVector( int* sv, int sanzahl);
friend ostream& operator<< ( ostream& os, const Vector& v );
};
#endif
vector.cpp
#include "vector.h"
Vector::Vector( int a ) : anzahl(a)
{
v = new int[a];
for ( int i = 0; i < a; i++ )
v[i] = i;
}
Vector::Vector( const Vector& vec )
{
anzahl = vec.getAnzahl();
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = vec[i];
}
Vector::~Vector()
{
delete[] v;
v = NULL;
}
bool kleiner( const int& a, const int& b )
{
return ( a < b );
}
int Vector::min() const
{
int min = v[0];
for ( int i = 1; i < anzahl; i++ )
{
if ( v[i] < min )
min = v[i];
}
return min;
}
int Vector::getAnzahl() const
{
return anzahl;
}
int Vector::operator[] ( const int i ) const
{
return v[i];
}
void Vector::setVector( int* sv, int sanzahl )
{
delete[] v; // alten Inhalt loeschen
anzahl = sanzahl;
v = new int[anzahl];
for ( int i = 0; i < anzahl; i++ )
v[i] = sv[i];
return;
}
ostream& operator<< ( ostream& os, const Vector& v )
{
for ( int i = 0; i < v.anzahl; i++ )
os << v[i] << ", ";
return os;
}

Declare the function outside of the class as well as specifying as a friend.
Reference; http://en.cppreference.com/w/cpp/language/friend
A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not accessible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided - see namespaces for details.
I think you and your Professor have different compilers?

Declare the friend function also outside the class definition in the header. It is not visiable until it will be declared outside the class.

Related

std::setw for the whole operator<< of user-defined type

We know, that the std::setw() influence only on the next output.
So, what standard practice to align
the whole operator<< of user-defined type in table output:
class A
{
int i, j;
public:
friend ostream& opeartor<<(ostream& out, const A& a) {
return << "Data: [" << i << ", " << j << "]";
}
}
// ...
A[] as;
out << std::left;
for (unsigned i = 0; i < n; ++i)
out << std::setw(4) << i
<< std::setw(20) << as[i] // !!!
<< std::setw(20) << some_strings[i]
<< some_other_classes[i] << std::endl;
out << std::right;
Just add a setw() method to your class:
class A
{
int i, j;
mutable int width = -1;
public:
A& setw(int n) {
this->width = n;
return *this;
}
friend ostream& operator<<(ostream& out, const A& a);
};
And when you print it, if you want to align, simply use it:
int main() {
A as[5];
for (auto & a : as)
cout << a.setw(15) << endl;
}

C++ Cycle through the addresses of an object

Objects (that are not dynamic) are blocks of data in memory.
Is there a way to cycle through and print each item in an object?
I tried doing it with 'this' but I keep getting errors.
#include "stdafx.h"
#include <iostream>
#include "TestProject.h"
using namespace std;
class myclass {
int someint = 10;
double somedouble = 80000;
int somearray[5] = {0, 1, 2, 3, 4};
public:
void somefunction();
};
void myclass::somefunction() {
cout << "\n test \n" << this;
myclass *somepointer;
somepointer = this;
somepointer += 1;
cout << "\n test2 \n" << *somepointer;
//Error: no opperator '<<' matches these operands
}
int main() {
myclass myobject;
myobject.somefunction();
return 0;
}
I'm guessing the error is because the types don't match. But I can't really figure a solution. Is there a dynamic type, or do I have to test the type somehow?
You must add friend global std::ostream operator << to display content of object
#include "stdafx.h"
#include <iostream>
using namespace std;
class myclass {
int someint;
double somedouble;
int somearray[5];
public:
myclass()
{
someint = 10;
somedouble = 80000;
somearray[0] = 0;
somearray[1] = 1;
somearray[2] = 2;
somearray[3] = 3;
somearray[4] = 4;
}
void somefunction();
friend std::ostream& operator << (std::ostream& lhs, const myclass& rhs);
};
std::ostream& operator << (std::ostream& lhs, const myclass& rhs)
{
lhs << "someint: " << rhs.someint << std::endl
<< "somedouble: " << rhs.somedouble << std::endl
<< "somearray: { ";
for (int iIndex = 0; iIndex < 5; iIndex++)
{
if (iIndex == 4)
lhs << rhs.somearray[iIndex] << " }" << std::endl;
else
lhs << rhs.somearray[iIndex] << ", ";
}
return lhs;
}
void myclass::somefunction() {
cout << "\n test \n" << this;
myclass *somepointer;
somepointer = this;
somepointer += 1; // wrong pointer to object with `object + sizeof(object)` address,
// data probably has been corrupted
cout << "\n test2 \n" << *somepointer; // displaying objects content
}
int main() {
myclass myobject;
myobject.somefunction();
return 0;
}
as you want to get to the object member using its pointers shifts I post another program
#include "stdafx.h"
#include <iostream>
using namespace std;
#pragma pack (push, 1) // force data alignment to 1 byte
class myclass {
int someint;
double somedouble;
int somearray[5];
public:
myclass()
{
someint = 10;
somedouble = 80000;
somearray[0] = 0;
somearray[1] = 1;
somearray[2] = 2;
somearray[3] = 3;
somearray[4] = 4;
}
void somefunction();
friend std::ostream& operator << (std::ostream& lhs, const myclass& rhs);
};
#pragma pack (pop) // restore data alignment
std::ostream& operator << (std::ostream& lhs, const myclass& rhs)
{
lhs << "someint: " << rhs.someint << std::endl
<< "somedouble: " << rhs.somedouble << std::endl
<< "somearray: { ";
for (int iIndex = 0; iIndex < 5; iIndex++)
{
if (iIndex == 4)
lhs << rhs.somearray[iIndex] << " }" << std::endl;
else
lhs << rhs.somearray[iIndex] << ", ";
}
return lhs;
}
void myclass::somefunction() {
int* pSomeInt = (int*)this; // get someint address
double *pSomeDouble = (double*)(pSomeInt + 1); // get somedouble address
int* pSomeArray = (int*)(pSomeDouble + 1); // get somearray address
std::cout << "someint: " << *pSomeInt << std::endl
<< "somedouble: " << *pSomeDouble << std::endl
<< "somearray: { ";
for (int iIndex = 0; iIndex < 5; iIndex++)
{
if (iIndex == 4)
std::cout << pSomeArray[iIndex] << " }" << std::endl;
else
std::cout << pSomeArray[iIndex] << ", ";
}
}
int main() {
myclass myobject;
myobject.somefunction();
return 0;
}
C++, by design, has no reflection feature. This means there is no generic, type-independent way to acces type metadata (e.g. the list of members if a class and their types) at runtime. So what you're trying to do (if I understand it correctly) cannot be done in C++.
Also I'm not sure what you meant by "objects (that are not dynamic)". all objects are blocks of data in memory, regardless of whether they are dynamically allocated or not.

Implementing Dijkstra's algorithm with vector of pointers

I'm working on a program involving Dijkstra's algorithm.
After searching long and far, I have only found help pertaining to Dijkstra's algorithm using Queues or Heaps, however, I am not using these. I have been tasked to used a vector of pointers to Vertex objects (a custom class I have defined).
I have attempted to convert the Queue pseudo code (from my textbook) to the best of my ability below:
void Dijkstra(vector<Vertex*> & V, int startNum)
{
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0);
insertionSort(sortedVertices);
while(sortedVertices.size() != 0)
{
sortedVertices[sortedVertices.size() - 1]->setKnown(true);
sortedVertices.pop_back();
insertionSort(sortedVertices);
Vertex * v = V[1]; // Will always bring the first element off the list
v->setKnown(true);
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++)
{
int dist = getAdjacentVertices()[m].getWeight();
if((sortedVertices[1].getDV() + dist) < sortedVertices[m+1]->getAdjacentVertices()[m].getDV())
{
//WE WILL DECREASE THE VALUE HERE by finding the distance between two vertices
cout << "It works so far" << endl;
// BOOK has this, somehow need to change it: w.path = v
}
}
}
}
However, when I attempt to compile, I keep receiving the following errors:
Main.cpp: In function 'void Dijkstra(std::vector<Vertex*>&, int)':
Main.cpp:154:42: error: base operand of '->' has non-pointer type 'std::vector<Vertex*>'
Main.cpp:156:44: error: 'getAdjacentVertices' was not declared in this scope
Main.cpp:157:35: error: request for member 'getDV' in 'sortedVertices.std::vector<_Tp, _Alloc>::operator[]<Vertex*, std::allocator<Vertex*> >(1ul)', which is of pointer type '__gnu_cxx::__alloc_traits<std::allocator<Vertex*> >::value_type {aka Vertex*}' (maybe you meant to use '->' ?)
Main.cpp:157:99: error: '__gnu_cxx::__alloc_traits<std::allocator<Edge> >::value_type' has no member named 'getDV'
I am trying to reduce the amount of Code in this post, but if need to be, my entire code is below:
Main.cpp:
#include "Vertex.h"
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <fstream>
using namespace std;
void shortestPath(vector<Vertex> & v);
template <typename Comparable>
void insertionSort(vector<Comparable> & a);
template <typename Comparable>
void insertionSort( vector<Comparable> & a, int left, int right );
///overload the less than operator in order to use the stl sort for vector
///print out the path for each vertex
int main()
{
/////READ ALL THE STUFF INTO THE GRAPH////
ifstream file;
file.open("graph.txt");
cout << "Opening file..." << endl;
if(!file)
{
cout << "System failed to open file.";
}
else
{
cout << "File successfully opened" << endl;
}
int numVertices;
int numEdges;
int num;
int adjacentVertex;
int weight;
file >> numVertices;
cout << "The number of vertices that are being read into the graph from the file: " << numVertices;
cout << endl;
vector<Vertex*> vertices;
//vector<Vertex> vertices(numVertices + 1);
Vertex * newVertex;
vertices.push_back(NULL);
cout << "SIZE: " << vertices.size() << endl;
cout << "NUM VERTICES: " << numVertices << endl;
for(int i=1;i < numVertices + 1; i++)
{
file >> numEdges;
cout << "At vertex " << i << " the number of edges is " << numEdges << endl;
newVertex = new Vertex();
//Using the i counter variable in the outer for loop to identify
//the what vertex what are currently looking at in order to read in the correct adjacent vertex and weight
cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
newVertex->setVertexNum(i);
//newVertex.setVertexNum(i);
for(int j=1;j<=numEdges;j++)
{
file >> adjacentVertex;
cout << "The adjacent vertex is: " << adjacentVertex << endl;
file >> weight;
cout << "The weight is: " << weight << endl;
cout << endl;
newVertex->setAdjacentVertex(adjacentVertex, weight);
}
//cout << "LENGTH OF VERTICES[i]: " << vertices.size() << endl;
vertices.push_back(newVertex);
}
file.close();
vector<Vertex*> sortedVertices = vertices;
insertionSort(sortedVertices);
cout << "SIZE: " << vertices.size() << endl;
for(int i=0;i<vertices.size();i++)
{
cout << "V" << i << ": ";
cout << endl;
if(vertices[i] != NULL)
{
cout << "DV Value: " << vertices[i]->getDV();
cout << endl;
cout << "Known Value: " << vertices[i]->getKnown();
cout << endl;
}
}
cout << "Sorted: " << endl;
for(int i=0;i<sortedVertices.size();i++)
{
cout << "V" << i << ": ";
cout << endl;
if(vertices[i] != NULL)
{
cout << "DV Value: " << sortedVertices[i]->getDV();
cout << endl;
cout << "Known Value: " << sortedVertices[i]->getKnown();
cout << endl;
}
}
//CALL THE SHORTEST PATH FUNCTION ON THE GRAPH/////
}
/*
const bool myFunction(const Vertex & x, const Vertex & y)
{
return (x.getDV() >= y.getDV());
}
*/
bool operator < (const Vertex & v1, const Vertex & v2)
{
return v1.getDV() > v2.getDV();
}
void Dijkstra(vector<Vertex*> & V, int startNum)
{
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0);
insertionSort(sortedVertices);
while(sortedVertices.size() != 0)
{
sortedVertices[sortedVertices.size() - 1]->setKnown(true);
sortedVertices.pop_back();
insertionSort(sortedVertices);
Vertex * v = V[1]; // Will always bring the first element off the list
v->setKnown(true);
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++)
{
int dist = getAdjacentVertices()[m].getWeight();
if((sortedVertices[1].getDV() + dist) < sortedVertices[m+1]->getAdjacentVertices()[m].getDV())
{
//WE WILL DECREASE THE VALUE HERE by finding the distance between two vertices
cout << "It works so far" << endl;
// BOOK has this, somehow need to change it: w.path = v
}
}
}
}
////////INSERTION SORT////////////
template <typename Comparable>
void insertionSort( vector<Comparable> & a )
{
for( int p = 1; p < a.size( ); ++p )
{
Comparable tmp = std::move( a[ p ] );
int j;
for( j = p; j > 0 && tmp < a[ j - 1 ]; --j )
a[ j ] = std::move( a[ j - 1 ] );
a[ j ] = std::move( tmp );
}
}
template <typename Comparable>
void insertionSort( vector<Comparable> & a, int left, int right )
{
for( int p = left + 1; p <= right; ++p )
{
Comparable tmp = std::move( a[ p ] );
int j;
for( j = p; j > left && tmp < a[ j - 1 ]; --j )
a[ j ] = std::move( a[ j - 1 ] );
a[ j ] = std::move( tmp );
}
}
Vertex.h:
#include "Edge.h"
#include <vector>
#include <climits>
#include <fstream>
using namespace std;
class Vertex
{
private:
int vertexNum; //number of the vertex for identification purposes
int degree;
bool known;
vector<Edge> adjacentVertices; //vector of vertices that are adjacent to the vertex we are currently looking at
int dv; //distance
int pv; //previous vertex
Vertex *vertex;
public:
Vertex()
{
dv = INT_MAX;
known = false;
}
void setKnown(bool Known)
{
known = Known;
}
bool getKnown()
{
return known;
}
void setVertexNum(int VertexNum)
{
vertexNum = VertexNum;
}
void setDegree(int Degree)
{
degree = Degree;
}
vector<Edge> & getAdjacentVertices()
{
return adjacentVertices;
}
int getVertexNum()
{
return vertexNum;
}
int getDegree()
{
return degree;
}
int getDV() const
{
return dv;
}
int setDV(int Dv)
{
dv = Dv;
}
void setAdjacentVertex(int AdjacentVertex, int Weight)
{
Edge newEdge;
newEdge.setWeight(Weight);
newEdge.setAdjVertex(AdjacentVertex);
adjacentVertices.push_back(newEdge);
}
friend ostream & operator <<(ostream & outstream, Vertex *vertex)
{
outstream << vertex->getVertexNum() << endl;
outstream << vertex->getDegree() << endl;
outstream << vertex->getKnown() << endl;
vector<Edge> E = vertex->getAdjacentVertices();
for(int x=0;x<E.size();x++)
{
outstream << E[x].getAdjVertex() << endl;
outstream << E[x].getWeight() << endl;
}
return outstream;
}
friend bool operator < (const Vertex & v1, const Vertex & v2);
};
Edge.h:
#include <cstdlib>
class Edge
{
private:
int adjVertex; //represents the vertex that the edge leads to
int weight;
public:
Edge()
{
adjVertex = 0;
weight = 0;
}
void setWeight(int Weight)
{
weight = Weight;
}
void setAdjVertex(int adjacent)
{
adjVertex = adjacent;
}
int getAdjVertex()
{
return adjVertex;
}
int getWeight()
{
return weight;
}
};
From g++ to English:
Main.cpp: In function 'void Dijkstra(std::vector<Vertex*>&, int)':
Main.cpp:154:42: error: base operand of '->' has non-pointer type 'std::vector<Vertex*>'
Main.cpp:156:44: error: 'getAdjacentVertices' was not declared in this scope
Main.cpp:157:35: error: request for member 'getDV' in 'sortedVertices.std::vector<_Tp, _Alloc>::operator[]<Vertex*, std::allocator<Vertex*> >(1ul)', which is of pointer type '__gnu_cxx::__alloc_traits<std::allocator<Vertex*> >::value_type {aka Vertex*}' (maybe you meant to use '->' ?)
Main.cpp:157:99: error: '__gnu_cxx::__alloc_traits<std::allocator<Edge> >::value_type' has no member named 'getDV'
Explanation:
for(int m = 0; m < sortedVertices->getAdjacentVertices().size(); m++) <- this is 154. sortedVertices is not a pointer. It is a std::vector of some pointers.
int dist = getAdjacentVertices()[m].getWeight(); <- 156. What is getAdjacentVertices?
sortedVertices[1].getDV() <- 157 sortedVertices[1] is a pointer. Look at operator[]
sortedVertices[m+1]->getAdjacentVertices() is a vector of Edge. Edge does not have a getDV() method defined.
Is this really your code?
As an author you should not have trouble understanding the error messages. Those are simple mistakes, that took 5 minutes for a stranger to understand. You need to put more effort in understanding what you write, and what compiler tells you. Or get some sleep to get some focus.
I would also suggest to spend some time working out what std::vector really is and how to understand std::vector<Vertex*> vector_of_vertices; object.
vector<Vertex*> sortedVertices = V;
sortedVertices[startNum]->setDV(0)
Here you create variable of type vector<Vertex*> on the stack. This is not a pointer. This is a container containing pointers of type Vertex* and that's completely different. You use -> operator which is only used on pointers.

need help on operator << overloading functions

The error I'm getting right now is:
multiple definition of operator<<(std::ostream&, SingleSequence& s)
the error location is at one of the overload operator function:
std::ostream& operator<<(std::ostream& os, const SingleSequence& s)
{
os << s.name << " " << s.seq << " " << s.length << " " << s.gccontent << " " << s.type;
return os;
}
This is the driver part:
#include"Sequences.h"
#include <iostream>
#include <fstream>
#include <cmath>
#include <ctime>
#include <cstdlib>
using namespace std;
int main(){
cout << "Assignment #1" << endl;
Sequences mysequences;
cout << mysequences;
cout << "Sorted by name" << endl;
mysequences.sortByName();
cout << mysequences;
cout << "Sorted by length" << endl;
mysequences.sortByLength();
cout << mysequences;
cout << "... done!" << endl;
}
This is the Sequences.h
#ifndef SEQUENCES_H_
#define SEQUENCES_H_
#include<string.h>
#include<strings.h>
#include<string>
#include<iostream>
using namespace std;
enum sequenceType { dna, rna, protein };
struct SingleSequence{
std::string name;
std::string seq;
int length;
double gccontent;
sequenceType type;
};
class Sequences {
public:
Sequences();
virtual ~Sequences();
int getListSize() const{return datasize;}
const SingleSequence& get( int i) const{
if (i>=0 && i < datasize)
return data[i];
throw OUT_OF_BOUNDS;;//{ if (i>=0 && i < datasize)
}
// return data[i];
// throw OUT_OF_BOUNDS;} // C++ has exceptions - you can even throw ints;
void sortByName();
void sortByLength();
friend std::ostream& operator<<(std::ostream& os, const SingleSequence& s) ;
friend std::ostream& operator<<(std::ostream& os, const Sequences& seqs) ;
int datasize;
private:
/*
* Remember to keep all data members private
*/
static const int MAX_LIST_SIZE = 20;
SingleSequence data[MAX_LIST_SIZE];
static const int OUT_OF_BOUNDS = -1;
};
std::ostream& operator<<(std::ostream& os, const SingleSequence& s)
{ os << s.name << " " << s.seq << " "
<< s.length << " " << s.gccontent << " "<<s.type;
return os;
}
#endif /* SEQUENCES_H_ */
-------------------------------------------------------------
This is the main cpp file
#include "Sequences.h"
#include <iostream>
using namespace std;
Sequences::Sequences() {
data[0] = { "KCNH2 Primer Pair 1 Forward", "CCAACTGGTGGACCGTCATT", 20, 55.0, dna };
data[1] = { "KCNH2 Primer Pair 1 Reverse", "GACAGCCAGGTGAACATCCA", 20, 55.0, dna };
data[2] = { "KCNH2 Primer Pair 2 Forward", "TGGATGTTCACCTGGCTGTC", 20, 55.0, dna };
data[3] = { "KCNH2 Primer Pair 2 Reverse", "CCACGGAACCTCTGGCAATA", 20, 55.0, dna };
data[4] = { "KCNH2 Primer Pair 3 Forward", "GAACGGAAGTGTGCCAACTG", 20, 55.0, dna };
data[5] = { "KCNH2 Primer Pair 3 Reverse", "ACAGCCAGGTGAACATCCAG", 20, 55.0, dna };
data[6] = { "KCNH2 Primer Pair 4 Forward", "CTGGATGTTCACCTGGCTGT", 20, 55.0, dna };
data[7] = { "KCNH2 Primer Pair 4 Reverse", "ATTTCCACGGAACCTCTGGC", 20, 55.0, dna };
data[8] = { "KCNH2 Primer Pair 5 Forward", "TGAAAACCGCTCGTCTGC", 18, 55.6, dna };
data[9] = { "KCNH2 Primer Pair 5 Reverse", "GGTGGAGCATGTGTTGTT", 18, 50.0, dna };
datasize = 10;
}
void Sequences::sortByName(){
for(int i = 0; i < 10; i++){
//int flag = 1;
SingleSequence temp;
for(int j = 0; j < 9; j++){
if (data[j].name.compare(data[j+1].name) > 0){
temp = data[j+1];
data[j+1] = data[j];
data[j] = temp;
}
}
}
}
void Sequences::sortByLength(){
for(int a = 0; a < 10; a++){
SingleSequence temp1;
for(int b = 0; b < 9; b++){
if (data[b].length > data[b+1].length){
temp1 = data[b+1];
data[b+1] = data[b];
data[b] = temp1;
}
}
}
}
std::ostream& operator<<(std::ostream& os, const Sequences& seqs)
{os << " Sequences object " << endl;
for (int i=0; i < seqs.getListSize(); i++ )
os << " " << (i+1) <<": " << seqs.get( i ) << endl;
return os;
}
You have two definition of the same operator << function in .h and .cpp. Hence, multi-definition error.
Keep the declaration in .h. Makes sure it is outside of the class
std::ostream& operator<<(std::ostream& os, const SingleSequence& s);
std::ostream& operator<<(std::ostream& os, const Sequences& seqs);
And write the definition in you .cpp file
std::ostream& operator<<(std::ostream& os, const Sequences& seqs)
{
os << " Sequences object " << endl;
for (int i = 0; i < seqs.getListSize(); i++)
os << " " << (i + 1) << ": " << seqs.get(i) << endl;
return os;
}
std::ostream& operator<<(std::ostream& os, const SingleSequence& s)
{
os << s.name << " " << s.seq << " "
<< s.length << " " << s.gccontent << " " << s.type;
return os;
}

C++: transfer a vector into a subprogram

In my example there are three similar vectors which I would like to print.
Could you help me understand how to transfer a vector into a subprogram so that not to
repeat myself?
#include "stdafx.h";
#include <vector>;
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
struct SPoint
{
int X;
int Y;
};
vector<SPoint> points;
vector<SPoint> selected;
vector<SPoint> cleared;
void print_points()
{
cout << "Points: "<< endl;
for (int i = 0; i < points.size(); i++)
{
cout << '('<<points[i].X <<',' <<points[i].Y <<')'<< endl;
}
cout << endl;
}
void print_selected()
{
cout << "Selected: "<< endl;
for (int i = 0; i < selected.size(); i++)
{
cout << '('<<selected[i].X <<',' <<selected[i].Y <<')'<< endl;
}
cout << endl;
}
void print_cleared()
{
cout << "Cleared: "<< endl;
for (int i = 0; i < cleared.size(); i++)
{
cout << '('<<cleared[i].X <<',' <<cleared[i].Y <<')'<< endl;
}
cout << endl;
}
int main ()
{
SPoint temp = {0, 0};
for (int i = 0; i < 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
for (int i = 5; i< 11;i++)
{
temp.X = i;
temp.Y = i;
points.push_back(temp);
}
print_points();
print_selected();
print_cleared();
system ("pause");
return 0;
}
You could do something like this:
void
print(const std::vector<SPoint>& vect, const std::string& message)
{
std::cout << message << ":" << std::endl;
for (int i = 0, size = vect.size(); i < size; ++i)
std::cout << vect[i].X << ":" << vector[i].Y << " ";
std::endl;
}
print(points, "Points");
print(points, "Selected");
print(points, "Cleared");
Good luck
To pass a vector as an argument to a function you do something like this:
void func(const vector<SPoint>& points) {
... do stuff
}
Then you call the function in you code like this:
...some stuff
vector<SPoint> a;
func(a);
Just use a const reference to a vector and pass it to the function:
void print(const vector<SPoint> &data) const {
}
...
print(points);
Here is a full C++ style approach:
struct SPoint
{
int X;
int Y;
};
std::ostream& operator <<( std::ostream& stream, SPoint const& point )
{
stream << '(' << point.X << ',' <<point.Y << ')';
return stream;
}
void print_vector( std::ostream& stream, std::vector< SPoint > const& vector )
{
std::copy(
points.begin(), points.end()
, std::ostream_iterator< SPoint >( std::cout, '\n' )
);
}
and then:
print_vector( std::cout, points );
print_vector( std::cout, selected );
print_vector( std::cout, cleared );