How to print out elements of vector of type pair?
here is a piece of my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
while(T--)
{
std::vector<std::pair<int, int> > *dragon;
std::vector<std::pair<int, int> > *villager;
dragon = new std::vector<std::pair<int, int> >;
villager = new std::vector<std::pair<int, int> >;
std::cin >> no_villages;
for(int i = 0; i<no_villages; i++)
{
std::cin >> number;
if(number < 0)
{
dragon->push_back(std::make_pair(number, i+1));
}
else if(number > 0)
{
villager->push_back(std::make_pair(number, i+1));
}
}
std::sort(dragon->begin(), dragon->end());
std::sort(villager->begin(), villager->end());
|
I now wish to print the elements of the vector. How do I do it?
A
std::pair has
.first and
.second member accessors.
1 2
|
for (auto v : *villager)
cout << "(" << v.first << "," << v.second << ")\n";
|
BTW, why are you dynamically allocating the
std::vector objects? Don't do that:
1 2 3 4 5 6
|
std::vector <std::pair <int, int> > dragon;
...
dragon.push_back( std::make_pair( ... ) );
...
std::sort( std::begin(dragon), std::end(dragon) );
...
|
Hope this helps.
Okay! No reason in particular as to why I was dynamically allocating memory. I will change that part. Thanks!
Topic archived. No new replies allowed.