warwcat
warwcat

Reputation: 339

vector accessing non zero elements but output as zero

I' did this program what suppose save pairs of string ,int on one vector and print the strings of the maximum number on vector but when i try to find this strings don't appears nothing so I try print all values of int's on vector and although was finding the maximum of 10 all values in the vector was printing as 0. Someone can explain was it occurred and how I can access the values , please.

#include <iostream>
#include <utility>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

typedef vector<pair<string,int>> vsi;

bool paircmp(const pair<string,int>& firste,const pair<string,int>&    seconde );

int main(int argc, char const *argv[]) {
 vsi v(10);

 string s;
 int n,t;

 cin>>t;

 for (size_t i = 0;i < t;i++) {
  for (size_t j = 0; j < 10; j++) {
   cin>>s>>n;
   v.push_back(make_pair(s,n));
  }
  sort(v.begin(),v.end(),paircmp);
  int ma=v[v.size()-1].second;
  cout<<ma<<endl;
  for (size_t j = 0; j < 10; j++) {
   cout << v.at(j).second  <<endl;
   if(v[j].second == ma)

   cout<<v[j].first<<endl;

  }

 }





return 0;
}

bool paircmp(const pair<string,int>& firste,const pair<string,int>& seconde ){
 return firste.second < seconde.second;
}

Upvotes: 0

Views: 41

Answers (1)

5gon12eder
5gon12eder

Reputation: 25439

This line

vsi v(10);

creates you a std::vector filled with 10 default-constructed std::pair<std::string, int>s. That is, an empty string and zero.

You then push_back other values to your vector but they happen to be sorted after those ten initial elements, probably because they all have positive ints in them.

Therefore, printing the first member of the first ten elements prints ten empty strings.

This is all I can guess from what you have provided. I don't know what you are trying to accomplish with this code.

Try something like

for (const auto& item : v)
  {
    std::cout << "{ first: '" << item.first << "', "
              << "second: " << item.second << " }\n";
  }

to print all elements of the vector v.

Upvotes: 1

Related Questions