Reputation: 1095
I am wanting to iterate through my entire column that contains the type double and divide each value by the size of the column. This will give me the frequency. I would have not issue doing this in an array or any other datatype. I am still learning about the vectors. Here is the 2D vector type that I am trying to manipulate
vector<pair<char, double>> output;
Upvotes: 0
Views: 1730
Reputation: 29724
std::pair is a struct template that provides a way to store two heterogeneous objects as a single unit.
if you have a vector of pairs
this means you will access data through pair interface . You can get first data of pair via first
member and second via second
.
for(std::vector<std::pair <char, double> >::const_iterator vpci = arg.begin();
vpci != arg.end(); ++vpci) {
cout << vpci->first << "->" << vpci->second;
}
or even better, maybe create a template:
template <typename T1, typename T2>
void prn_vecOfPair(const std::vector<std::pair <T1, T2> > &arg, string sep ="") {
for(std::vector<std::pair <T1, T2> >::const_iterator vpci = arg.begin();
vpci != arg.end(); ++vpci) {
cout << vpci->first << "->" << vpci->second << sep;
}
}
in C++11 this (as usual) can be done much easier:
for (auto & i : output)
{
cout << i->first << "->" << i->second << "\n";
}
Upvotes: 1
Reputation: 45410
If you have C++11:
for (auto & p : output)
{
cout << p.first << " " << p.second << "\n";
}
std::cout << std::endl;
or with C++03
for (std::vector<std::pair<char, double> >::iterator it = output.begin();
it != output.end(); ++it)
{
cout << it .first << " " << it .second << "\n";
}
std::cout << std::endl;
Upvotes: 2
Reputation: 37132
You can treat a vector just like an array, and access the elements using []
. For example:
for (size_t i = 0; i < output.size(); ++i)
{
pair<char, double>& element = output[i]; // access element i in the vector
cout << element.first; // prints the first member of the pair
cout << element.second; // prints the second member of the pair
}
Upvotes: 1