Reputation: 79
I am trying to use STl sort on a vector which is a part of a 2d array, but getting an error. What is the correct way to do this? Trying to use vector normally as sort(A,A+A.size()) where A is the vector.
I have added a comment at the sort statement that is giving an error.
#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
while(1)
{
int m,n;
cin>>m>>n;
int arr[m][n];
for(int x=0;x<m;x++)
for(int y=0;y<n;y++)
cin>>arr[x][y];
vector<int> cost[m][n]; //THIS IS THE 2-D ARRAY OF VECTORS
cost[0][0].push_back(arr[0][0]);
for(int i=1;i<m;i++)
{
cost[0][i].push_back(cost[0][i-1][0]+arr[0][i]);
}
for(int i=1;i<n;i++)
{
cost[i][0].push_back(cost[i-1][0][0]+arr[i][0]);
}
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
vector<int>::iterator it;
for(it=cost[i-1][j].begin(); it!=cost[i-1][j].end();it++)
cost[i][j].push_back(((*it)+arr[i][j]));
vector<int>::iterator it1;
for(it1=cost[i][j-1].begin(); it1!=cost[i][j-1].end();it1++)
cost[i][j].push_back(((*it1)+arr[i][j]));
//freevec(cost[i][j]);
}
}
int tx,ty,k;
cin>>tx>>ty>>k;
//THIS STEP IS GIVING AN ERROR.
sort(cost[tx][ty],cost[tx][ty]+cost[tx][ty].size());
//THIS STEP IS GIVING AN ERROR.
cout<<cost[tx][ty][k-1]<<endl;
/*
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{ cout<<"\n\n"<<arr[i][j]<<endl;
vector<int>::iterator it;
for(it=cost[i][j].begin(); it!=cost[i][j].end();it++)
cout<<(*it)<<" ";
}
cout<<endl;
}*/
}
}
Upvotes: 0
Views: 55
Reputation: 227418
A vector doesn't change its properties by being an element of an array. So you would sort it just like you would sort a vector that is not an element of a 2D array:
sort(cost[tx][ty].begin(), cost[tx][ty].end());
or
sort(begin(cost[tx][ty]), end(cost[tx][ty]));
Assuming argument dependent lookup finds std::sort
, std::begin
and std::end
.
Upvotes: 4