Page 1 of 1
2D string array for STL sort
Posted: Fri Jan 26, 2007 10:11 am
by soyoja
I'm so awkward using in STL. When I implemented 2D array sort in C, I used bubble sort.
But I want to know how can I sort 2D array in STL sort().
For example,
Code: Select all
// before sort
string data[3][2] = { {"cab","hello"}, {"cba","world"}, {"abc","haha"}};
// After sort
string data[3][2] = { {"abc","haha"}, {"cab","hello"}, {"cba","world"}};
In this array, I want sort to use first elements of data array.
How can I wrote comp() function for my sort() method??
Code: Select all
// I'll use like this
sort( &data[0], data[3], comp );
Posted: Mon Jan 29, 2007 10:51 am
by mohiul alam prince
hello
maximum time i solve this type of problem by this way
Code: Select all
#include <stdio.h>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct Node {
vector <string> S;
};
vector <Node> V;
bool cmp(Node A, Node B) {
int i;
for (i = 0; i < A.S.size() && i < B.S.size(); i++) {
if (A.S[i] < B.S[i])
return true;
if (A.S[i] > B.S[i])
return false;
}
if (A.S.size() < B.S.size())
return true;
return false;
}
int main() {
int i, j;
V.clear();
Node A;
A.S.clear();
A.S.push_back("cab"); A.S.push_back("hello"); A.S.push_back("abc");
V.push_back(A);
A.S.clear();
A.S.push_back("cba"); A.S.push_back("world");
V.push_back(A);
A.S.clear();
A.S.push_back("abc"); A.S.push_back("haha");
V.push_back(A);
A.S.clear();
A.S.push_back("abc"); A.S.push_back("haha"); A.S.push_back("world");
V.push_back(A);
A.S.clear();
A.S.push_back("cba"); A.S.push_back("abc");
V.push_back(A);
A.S.clear();
A.S.push_back("cab"); A.S.push_back("hello"); A.S.push_back("a");
V.push_back(A);
sort(V.begin(), V.end(), cmp);
for (i = 0; i < V.size(); i++) {
for (j = 0; j < V[i].S.size(); j++) {
printf("%s ", V[i].S[j].c_str());
}
printf("\n");
}
return 0;
}
Thankx
MAP
Posted: Sat Feb 03, 2007 9:18 am
by A1
I would rather like to put the 2D array in a 1D string array or in a vector<string> and then sort.
in that case the comp function would be:
Code: Select all
bool comp(string a, string b){
return a<b;
}
for loops in comp function seems more costly then: 2D -> 1D -> sorted 1D -> again 2D

Posted: Thu Jun 21, 2007 1:28 pm
by saman_saadi
I think you cannot use two dimensional array in sort function:
Code: Select all
int a[3][2] = {{1, 2}, {3, 4}, {5, 6}};
sort(a, a + 3); // Syntax eror
for solving this problem you must use vector:
Code: Select all
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
void print(vector<string> data[])
{
int i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 2; j++)
cout << data[i][j] << ' ';
cout << endl;
}
}
int main()
{
string data[3][2] = { {"cab","hello"}, {"cba","world"}, {"abc","haha"}};
vector< string > v[3] =
{vector< string >(data[0], data[0] + 2),
vector< string >(data[1], data[1] + 2),
vector< string >(data[2], data[2] + 2)};
print(v);
cout << endl;
sort(v, v + 3);
print(v);
return 0;
}