Understanding Vector classes and Tournament selection - c++

I want to be able to compare the "overall" values of a person with another person. I'm unsure if I'm storing them correctly and I don't know how to compare them correctly. I don't know how to access the "overall" values of any single person, which is what I think is bugging me the most.
Header file
#ifndef Population_h
#define Population_h
class population
{
friend class person;
private:
int size;
int generation;
public:
void setsize(int x);
void tournament_selection(population x, int z);
};
class person
{
friend class population;
private:
float fit1;
float fit2;
float overall;
public:
void generatefit();
void setfit();
void langerman();
void printinfo();
};
#endif
Population.cpp
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <random>
#include <string>
#include <CMATH>
#include <vector>
#include "Population.h"
using namespace std;
void person ::generatefit()
{
float randomnumb1;
float randomnumb2;
//float((rand() % 10)*0.1);
randomnumb1 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
randomnumb2 = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
fit1 = randomnumb1;
fit2 = randomnumb2;
}
void person::setfit()
{
float x = fit1;
float y = fit2;
}
void person::langerman()
{
overall = 3 * pow(fit1, 2) + 2 * fit2 + 0.0252;
for (overall; overall > 1; overall--);
}
void person::printinfo()
{
cout << overall << " " << endl;
}
void population::setsize(int x)
{
size = x;
}
void population::tournament_selection(population x, int total)
{
float best = 0;
for (int i = 0; i <= total; i++)
{
}
}
main.cpp
#include "Population.h"
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <random>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
cout << "Program is starting " << endl;
srand(static_cast <unsigned> (time(0)));
population pop;
vector<person> popvector;
vector<person> survivor;
person *p1;
int popsize = 500;
pop.setsize(popsize);
for (int i = 0; i <= popsize; i++)
{
p1 = new person;
p1 ->generatefit();
p1->setfit();
p1->langerman();
popvector.push_back(*p1);
delete p1;
}
cout << "The fit values of the person are listed here: " << endl;
vector<person> ::iterator it; //iterator to print everything in the vector
for (it = popvector.begin(); it != popvector.end(); ++it)
{
it->printinfo();
}
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); // generate a seed for the shuffle process of the vector.
cout << "Beggining selection process" << endl;
shuffle(popvector.begin(), popvector.end(), std::default_random_engine(seed));
//want to pick consecutive parents
int j = 0;
}
I want to be able to compare people, store the "winners" into the "survivors" vector and then proceed to use the "survivor" vector to create a new population with the use of crossover and mutation for X generations.

You could use operator overloading to set a customized "Rule" of comparing the fitness level of two human beings. std::string is a perfect example": equal operations can be carried out directly by if(str1 == str2) instead of if(!strcmp(str1, str2)), demonstrating the virtue of operator overloading technique.
The following code should suit your needs:
class person {
friend class population;
private:
float fit1;
float fit2;
float overall;
public:
void generatefit();
void setfit();
void langerman();
void printinfo();
//Overloading '<' operator
bool operator(const person&);
};
//The following function defines
//rule of fitness in the jungle
bool person::operator < (const person& p2){
//This is just an example, you can define your own rules
return overall < p2.overall;
}
Once the comparing rule has been established, you can sort your population by that very rule:
//The "less fit" rule is defined so the population will be sorted
//in ascending order, if you want to sort them by descending order,
//just change the definition of your fitness rules accordingly.
sort(popvector, popvector + popsize);
Or you can use an ordered container to store population in the first place. Such choice can be set, map or priority_queue. The elements in ordered container will always follow the exact order you designated when you declared such container objects.
In your case I would suggest priority_queue because you can easily pop out the most unfitful human being from the top of the pile, like this:
#include<priority_queue>
//Still, the definition of "priority" is required beforehand
priority_queue<person> pqPerson;
person tmp;
for(int i = 0; i < popsize; ++i){
tmp.setfit(fit1, fit2, overall);
pqPerson.push(tmp);
}
for(int generation = 0; generation < X; +=generation){
//The weakest group will perish
for(int j = 0; j < tollSize; ++j){
pqPerson.pop();
}
//Crossover and Mutation process
}

Related

Cout from class method does nothing

I have a class "beaker" that represents a beaker with n-dices that have n-faces. It has a method "roll" which returns a vector with n-elements where each element represents a dice. Then I have another class "board" that for now, it only prints the values generated by beaker.roll using cout;
So I call the beaker.roll function to pass the result to print them, but it does nothing. I have no compile errors/IntelliSense warnings. What am I doing wrong?
#include <iostream>
#include <random>
#include <chrono>
#include <thread>
#include <vector>
using std::cout;
using std::vector;
class beaker {
public:
int diceCount, diceFaces;
beaker() {
diceCount = 2;
diceFaces = 6;
};
beaker(int count, int faces) {
diceCount = count;
diceFaces = faces;
};
//Dice values
vector<uint8_t> dice;
//METHODS
//RETURN DICE i VALUE
int diceValue(int d) {
return dice.at(d-1);
}
//ROLL DICE + RETURN RESULT
vector<uint8_t> roll() {
std::mt19937 mt(std::chrono::high_resolution_clock::now().time_since_epoch().count());
std::uniform_int_distribution<int> dist(1, diceFaces);
for (int i=0; i<diceCount; i++) {
dice.push_back(dist(mt));
}
return dice;
}
//RETURN LAST DICE NUMBERS
vector<uint8_t> result() {
return dice;
}
};
class board {
public:
void Print(vector<uint8_t> dice) {
for (int i=0; i<dice.size(); i++) {
cout << dice.at(i);
}
}
};
int main() {
beaker beaker;
board board;
board.Print(beaker.roll());
}
The problem is that the values in dice are of type uint8_t, which the cout::<< operator is interpreting as unsigned char, so it is printing out the values as ASCII characters. However, the values are between 1 and 6, and ASCII characters less than 32 are mostly non-printing characters, so they aren't visible in the output.
To convince the cout::<< operator to print the values as integers instead, update the code to this:
void Print(vector<uint8_t> dice) {
for (int i=0; i<dice.size(); i++) {
cout << static_cast<int>(dice.at(i));
}
cout << std::endl; // just to make sure the buffer gets flushed ASAP
}

c++ vector's member are not updating

Im trying to write a adjacency matrix representation using vectors of integer vectors , therefore vector> . However when I add members to the vector and later try and print those values nothing has changed. Most likely it has to do with "pass by value" however I have used "pass by reference" to the best of my knowledge.
Here is my header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight);
void print_graph();
private:
std::vector<std::vector<int>> vertex_matrix;
int num_of_vertices;
int num_of_edges;
};
#endif
the cpp implementation file:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices)
{
if (_num_of_vertices==0)
{
_num_of_vertices=10;
}
for (int i = 0; i < _num_of_vertices; i++)
{
vertex_matrix.push_back(vector<int> (_num_of_vertices,INT_MAX));
}
}
graph::~graph()
{
vertex_matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight)
{
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
}
void graph::print_graph()
{
for (int i=0; i< vertex_matrix.size(); i++)
{
for (int j = 0; j < vertex_matrix.size(); j++)
{
//vertex_matrix[i][j]
std::vector<int> columnVector = vertex_matrix[i];
if (columnVector[j] != INT_MAX)
{
std::cout << columnVector[j] ;
}
else
{
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
the main entry:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
_graph.add_edge(1,2,1);
_graph.add_edge(2,3,1);
_graph.add_edge(3,1,1);
_graph.add_edge(3,3,1);
_graph.add_edge(3,4,1);
_graph.add_edge(4,0,0);
_graph.print_graph();
}
When I use the print function I currently getting 0's.
How can I make this proper pass by reference, and have the updated values print.
Thanks
As stated in the comments, you are creating a copy of your column and then modifying the copy. What you want to do is to make a reference to it.
vector<int>& columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
Or you can access the element directly.
if (vertex_matrix[v1-1][v2-1] == INT_MAX)
{
vertex_matrix[v1-1][v2-1] = weight;
}
In print_graph you are doing the same, but here you are not modifying anything so that works, but you are making an unnecessary copy for no reason which is not ideal.
A last point is that you are calling vertex_matrix.clear() in your destructor. This is redundant, when the vector goes out of scope it will clear itself up, so you don't need to manage that.

c++ segmentation fault trying to access vector

Im trying to create a adjacency representation of a graph.
I wrote a small program using vectors of vectors , however I keep getting "segmentation fault" but the compiler(clang++ version 5.0.1 on Windows) it seems wereever I try to access the vector vertex_matrix its giving a segmentation fault, why is it not being instantiated?
Here is the header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight);
void print_graph();
private:
std::vector<std::vector<int>> vertex_matrix;
int num_of_vertices;
int num_of_edges;
};
#endif
Here is the cpp implementation:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices)
{
if (_num_of_vertices==0)
{
_num_of_vertices=10;
}
for (int i = 0; i < _num_of_vertices; i++)
{
vertex_matrix[i]=(vector<int> (_num_of_vertices,INT_MAX));
}
}
graph::~graph()
{
vertex_matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight)
{
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = vertex_matrix[v1-1];
if (columnVector[v2-1] == INT_MAX)
{
columnVector[v2-1] = weight;
}
}
void graph::print_graph()
{
cout << "vertex_matrix size:" << vertex_matrix.size() << endl;
for (int i=0; i< num_of_vertices; i++)
{
for (int j = 0; j < num_of_vertices; j++)
{
//vertex_matrix[i][j]
std::vector<int> columnVector = vertex_matrix[i];
if (columnVector[j] != INT_MAX)
{
std::cout << columnVector[j] ;
}
else
{
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
Here is the main entry:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
_graph.add_edge(1,2,1);
_graph.add_edge(2,3,1);
_graph.add_edge(3,1,1);
_graph.add_edge(3,3,1);
_graph.add_edge(3,4,1);
_graph.add_edge(4,0,0);
_graph.print_graph();
}
I edited the above code to use pass by reference, however the matrix still prints as 0's.
Please help with pass by reference, updates below:
Header:
#ifndef GRAPH_MATRIX
#define GRAPH_MATRIX
#include <vector>
//header for graph represented via adjacency matrix with minimal functionality
class graph
{
public:
graph(int);
~graph();
void add_edge(int v1, int v2, int weight,std::vector<std::vector<int>> & matrix);
void print_graph();
std::vector<std::vector<int>> vertex_matrix;
private:
int num_of_vertices;
int num_of_edges;
};
#endif
Cpp file:
#include <iostream>
#include "graph_matrix.h"
#include <climits>
using namespace std;
//header for graph represented via adjacency matrix with minimal functionality
graph::graph(int _num_of_vertices) : num_of_vertices(_num_of_vertices) {
if (num_of_vertices == 0) {
num_of_vertices = 10;
}
for (int i = 0; i < num_of_vertices; i++) {
std::vector<std::vector<int>>& matrix = vertex_matrix;
matrix.push_back(vector<int> (num_of_vertices, INT_MAX));
}
}
graph::~graph() {
std::vector<std::vector<int>>& matrix = vertex_matrix;
matrix.clear();
}
void graph::add_edge(int v1, int v2, int weight,std::vector<std::vector<int>> & _matrix) {
//vertex_matrix[v1-1][v2-1] == INT_MAX
vector<int> columnVector = _matrix[v1 - 1];
if (columnVector[v2 - 1] == INT_MAX) {
columnVector[v2 - 1] = weight;
}
}
void graph::print_graph() {
std::vector<std::vector<int>>& matrix = vertex_matrix;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.size(); j++) {
//vertex_matrix[i][j]
std::vector<int> columnVector = matrix[i];
if (columnVector[j] != INT_MAX) {
std::cout << columnVector[j];
} else {
std::cout << "0";
}
}
std::cout << endl;
}//end for printing
}
main:
#include <iostream>
#include "graph_matrix.h"
using namespace std;
int main ()
{
std::cout << " Matrix representation of graph" << std::endl;
graph _graph(4);
std::vector<std::vector<int>>& m = _graph.vertex_matrix;
_graph.add_edge(1,2,1,m);
_graph.add_edge(2,3,1,m);
_graph.add_edge(3,1,1,m);
_graph.add_edge(3,3,1,m);
_graph.add_edge(3,4,1,m);
_graph.add_edge(4,0,0,m);
_graph.print_graph();
}
Any help will be appreciated.
Thanks
You create an empty vector and then try to access elements in it. Change your constructor to
graph::graph(size_t _num_of_vertices) :
vertex_matrix(
std::vector<std::vector<int>>(
_num_of_vertices,std::vector<int>(_num_of_vertices)
)
)
{}
to create a correctly sized vector.
Also in case _num_vertices == 0 you set it to 10 but thats after you initialized the member num_vertices so you leave the object in an inconsistent state. There are different ways to fix that, I would probably just throw an exception when the number of vertices passed is zero, or just ignore it. User wants a zero sized matrix? Why not?
Moreover the size should be unsigned not signed, there is size_t for container sizes. Even better you shouldnt have that member at all, because a vector already knows its size, the only reason to repeat that information is to introduce mistakes ;)

How to debug a C++ segfault?

Apparently since its a segfault the C++ compiler won't output anything? I'm having some trouble with some C++ code I wrote. I'm a novice and I've been looking for this segfault for some time now... I can't figure it out.
My best guess is it is somewhere in the Deck() constructor, can anyone give me a hand?
Any help would be appreciated!
Thanks!
Follow up: In the future, does anyone have any good methods of debugging segfaults?
Deck.cpp
#include "Deck.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using std::ostream;
using std::vector;
const string Deck::RANKS[13] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
const string Deck::SUITS[4] = {"H","D","C","S"};
string cards[52];
int card = 0;
Deck::Deck() : size(0)
{
for (int i = 0; i < 13; i++)
{
for (int j = 0; j < 4; j++)
{
cards[size] = RANKS[i] + SUITS[j];
size++;
}
}
shuffle();
}
Deck::~Deck() {}
void Deck::shuffle()
{
size = MAX_SIZE;
std::random_shuffle(&cards[0], &cards[MAX_SIZE-1]);
}
string Deck::getCard()
{
card++;
return cards[card-1];
}
Deck.h
#ifndef DECK_H
#define DECK_H
#include <ostream>
#include <string>
#include <vector>
using std::ostream;
using std::string;
using std::vector;
class Deck
{
private:
static const int MAX_SIZE = 52;
static const string RANKS[13];
static const string SUITS[4];
static const string DECK[52];
int size;
public:
Deck();
~Deck();
void shuffle();
string getCard();
int getDeckSize() const {return size;}
friend ostream& operator<<(ostream&, const Deck&);
};
#endif
Main.cpp
#include <iostream>
#include "Deck.h"
using namespace std;
int main()
{
int pairs = 0;
for(int x = 0; x < 100; x++)
{
cout << "yep";
Deck deck;
cout << "awooga";
deck.shuffle();
cout << "hai";
string cards[2];
cards[0] = deck.getCard();
cards[1] = deck.getCard();
for(int y = 0; y < 5; y++)
{
string tempCard = deck.getCard();
if(cards[0].compare(tempCard) == 0 || cards[1].compare(tempCard) == 0)
{
pairs++;
}
}
}
cout << pairs;
return 0;
}
Your problem is that getCard has side effects, increasing the value of card every time you call it. As soon as you call it more than 52 times, your program may crash. Note that card is a global variable and doesn't reset to zero whenever you create a new deck.
I also noticed that your call to random_shuffle has an off-by-one error. The end iterator needs to be one beyond the actual end of your container, not pointing at the end (so it's a half-open range).
Finally for debugging segmentation faults in general, enable core dumps on your system and use gdb to attach the core to your binary. That will sometimes give you a good clue where to start.

Templates C++ error : could not deduce template argument

I am trying ot add a function template that will print if it contains precision values or valves and the value. The rest of the program works except this function. I am not sure what I am doing wrong but the error I recieve is:
error C2784: 'void printInstrumentDetail(const I *const )' : could not deduce template argument for 'const I *const ' from 'std::vector<_Ty>'
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include "Instruments.h"
#include "Brass.h"
#include "Strings.h"
using namespace std;
//template<typename I> <---Problem
//void printInstrumentDetail(const I * const a)
//{
// for (size_t i = 0; i < 6; i ++)
// {
// cout << "The details for " << a[i]->getName()
// << ": " << a[i]->print();
// }
//}
int main()
{
double total = 0;
Strings violin("Violin", 553.90, 3);
Strings cello("Cello", 876.45, 3);
Strings viola("Viola", 200.50, 23);
Brass tuba("Tuba", 1400.10, 1.23);
Brass trumpet("Trumpet", 500.00, 4.32);
Brass sax("Sax", 674.78, .99);
vector <Instruments *> band(6);
band[0] = &violin;
band[1] = &tuba;
band[2] = &cello;
band[3] = &trumpet;
band[4] = &viola;
band[5] = &sax;
cout << fixed << setprecision(2);
cout << "The instruments in the band are:\n";
//Get name and cost of each
for (size_t i = 0; i < 6; i ++)
{
cout << band[i]->getName() << " $"
<< band[i]->getCost() << endl;
}
cout << "\nThen band is warming up..." << endl;
//Get descrition of how sound is made of each
for (size_t i = 0; i < 6; i ++)
{
cout << "This " << band[i]->getName()
<< " makes sounds by " ;
band[i]->playSound();
}
cout << "\nTotal cost of the band is: $" ;
//Get total cost of all instruments
for (size_t i = 0; i < 6; i ++)
{
total = band[i]->getCost() + total;
}
cout << total << endl;
//printInstrumentDetail(band); <--Problem
return 0;
}
Here's the base class:
#ifndef INSTRUMENTS_H
#define INSTRUMENTS_H
#include <string>
using namespace std;
class Instruments
{
public:
Instruments(string, double);
void setName(string);
virtual string getName();
void setCost(double);
virtual double getCost();
virtual void print();
virtual void playSound();
private:
string name;
double cost;
};
#endif
#include <iostream>
#include "Instruments.h"
using namespace std;
Instruments::Instruments(string n, double c)
{
name = n;
cost = c;
}
void Instruments::setName(string n)
{
name = n;
}
string Instruments::getName()
{
return name;
}
void Instruments::setCost(double c)
{
cost = c;
}
double Instruments::getCost()
{
return cost;
}
void Instruments::print()
{
}
void Instruments::playSound()
{
//empty
}
Derived class Bass:
#ifndef BRASS_H
#define BRASS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Brass : public Instruments
{
public:
Brass(string, double, double);
void setPrecisionValue(double);
double getPrecisionValue();
void print() ;
void playSound();
private:
double precision;
string sound;
};
#endif
#include <iostream>
#include "Brass.h"
using namespace std;
Brass::Brass(string n, double c, double p)
:Instruments(n, c)
{
precision = p;
}
void Brass::setPrecisionValue(double p)
{
precision = p;
}
double Brass::getPrecisionValue()
{
return precision;
}
void Brass::print()
{
cout << getPrecisionValue() << endl;
}
void Brass::playSound()
{
cout << "blowing in a mouthpiece." << endl;
Instruments::playSound();
}
Derived class Strings:
#ifndef STRINGS_H
#define STRINGS_H
#include <string>
#include "Instruments.h"
using namespace std;
class Strings : public Instruments
{
public:
Strings(string, double, int);
void setValves(int);
int getValves();
void print();
void playSound();
private:
int valves;
};
#endif
#include <iostream>
#include "Strings.h"
using namespace std;
Strings::Strings(string n, double c, int v)
:Instruments(n, c)
{
valves = v;
}
void Strings::setValves(int v)
{
valves = v;
}
int Strings::getValves()
{
return valves;
}
void Strings::print()
{
cout<< getValves() << endl;
}
void Strings::playSound()
{
cout << "striking with a bow." << endl;
Instruments::playSound();
}
Well, the problem is that your template requires a pointer:
template<typename I>
void printInstrumentDetail(const I * const a);
but you're giving it a vector, not a pointer:
vector <Instruments *> band(6);
...
printInstrumentDetail(band);
You can hack your way around this by passing a pointer to the printInstrumentDetail function, like so:
printInstrumentDetail(&band[0]);
But really, you'd be much better off modifying printInstrumentDetail to take a container or a pair of iterators:
template <typename ContainerT>
void printInstrumentDetail(const ContainerT& a)
or
template <typename IteratorT>
void printInstrumentDetail(IteratorT first, IteratorT last)
with the appropriate modifications to the definition of the function.
Pass the pointer to vector
printInstrumentDetail(&band);
and inside printInstrumentDetail
(*a)[i]->getName();
Well, first off I don't believe you can pass a vector as a const * I const at
printInstrumentDetail(band);
Vector cannot be just cast to a pointer. One working solution would be something like:
template <typename T>
void printInstrumentDetail( const std::vector<T*>& band )
{
for ( size_t i = 0; i < band.size(); ++i )
cout << "The details for " << band[i]->getName()
<< ": " << band[i]->print();
}
And there are many others, including iterators, functors, STL algorithms, etc.
You are trying to pass an object to an interface that wants a pointer.
void printInstrumentDetail(const I * const a)
Convert this to a reference.
void printInstrumentDetail(I const I& a)
But to conform to the pattern that is common in C++. You should pass the beginning and end of the sequence as parameters. ie change your function to take itertors rather than a pointer.
Instead of passing the pointer:
printInstrumentDetail(const I * const a)
you can pass the reference:
printInstrumentDetail(const I& a)
Everything else stays unchanged.
First of all, there seems to be no reason for PrintInstrumentDetail to be a template at all -- it works with pointers to the base class, and unless you're likely to have other types with getName() and print() members to which it might be applied, it can/could/should just work with pointers to the base class.
Second, I'd think hard about changing how you do the job. Instead of a member function in each Instrument, and PrintInstrumentDetail to loop over all the instruments, I'd think hard about defining operator<< for Instrument, and using a standard algorithm to print out the details.
Looking at it, I think a few other things should change as well. First of all, unless you're dealing with really unusual instruments, the number of valves on a brass instrument is fixed forever -- so it should NOT have a SetValve() member. Rather, the number of valves should be set during construction, but not be open to change afterwards.
String instruments don't have valves at all (at least most normal ones don't), so they shouldn't have SetValves(), GetValves(), or anything else related to valves.
Likewise, unless you're doing something pretty unusual, the cost of an instrument can never change -- you paid what you paid, so the cost should be set during construction, and not open to later alteration.
Edit: one other thing: instead of hard-coding 6 everywhere, use band.size() to loop over all the instruments in the band.