-2

In the following code, I have a 2D vector,in each index of vector each pair contains int and string. I am trying to access the each element after taking the values in the vector. Suggestions will be very much appreciated.

 #include <bits/stdc++.h>
 using namespace std;
 vector<pair<int,string>> aye[101];

int main()
{ int n,m,i,a,b;
  string x;
cin >> n >> m;
for (int i = 1; i <= n; ++i)
{
    cin >> x;
    cin >> a >> b;
    aye[a].push_back(make_pair(-b,x));
    cout<<aye[a].first<<aye[a].second;//this is not working
    cout<<aye[a][0]<<aye[a][1]<<endl;//this is not working

 }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Shovo
  • 133
  • 2
  • 9

2 Answers2

1

You seem to be confused by your 2d array structure (I have to admit, I am also a bit confused why you use something like that). This:

aye[a]

Is the (a+1)th element of the array, which is a vector, then

aye[a][i]

is the (i+1)th element in that vector, which is a pair and

aye[a][i].first
aye[a][i].second

are the first/second entries of that pair, respectively.

However, I have my doubts that you really need an array of vectors of pairs, especially as you seem to ignore one of the dimensions in the rest of the code.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

You seem to be trying to print the element that you just added to the vector to do that, I'd suggest the use of vector::back. You could replace your two non-working lines with something like this:

cout << aye[a].back().first << ' ' << aye[a].back().second;

Live Example


Whatever your intent with this structure, the inputted values of a pose a threat to your design:

  1. There is no check to see that thy fall between 0 and 100
  2. You allocate 101 elements before even knowing n which means that 101 - n of these elements are wasted.

In this situation I believe using a map for your first dimension would be a far better plan; so you're structure would look like:

map<int, vector<pair<int, string>>> aye;

No further changes would need to be made to your code, but you would allocate only n vector<pair<int, string>>s whether n was larger or smaller than 101.

Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288