C++ compilation error when I use predicate friend function in the std::sort()


 
Thread Tools Search this Thread
Top Forums Programming C++ compilation error when I use predicate friend function in the std::sort()
# 1  
Old 03-17-2012
C++ compilation error when I use predicate friend function in the std::sort()

Hi,

Can anyone tell me why the following program is giving compiler error when I use a friend function of a class as the comparison predicate for the third parameter of std::sort() algorithm? How to correct it, keep the 'friend' intact?

Code:
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>

using namespace std;

class A {
    inline friend bool comp(const A& o1, const A& o2) {
        return o1.data < o2.data; // binary predicate function
    }

    inline friend bool operator < (const A& o1, const A& o2) {
        return o1.data < o2.data; // overloaded 'operator < ()' function
    }
public:
    int data;
    A(int i = 0) : data(i) { }
    inline int getVal() const { return data; }
};

struct great {
    bool operator() (const A& lx, const A& rx) const {
        return lx.data < rx.data;
    }
};

int main() {
    A a(60), b(20), c(50);
    std::vector<A> v;
    std::list<A> ll;

    v.push_back(a);
    v.push_back(b);
    v.push_back(c);

    std::sort(v.begin(), v.end(), comp); // std::sort() called with predicate
    std::sort(v.begin(), v.end(), great());

    for (vector<A>::const_iterator itr1 = v.begin(); itr1 != v.end(); ++itr1) {
        cout << (*itr1).getVal() << endl;
    }

    ll.push_back(a);
    ll.push_back(b);
    ll.push_back(c);

    ll.sort(); // internally calls overloaded operator < ()

    for (list<A>::const_iterator itr2 = ll.begin(); itr2 != ll.end(); ++itr2) {
        cout << (*itr2).getVal() << endl;
    }

    list.sort(comp); // uses predicate in the sort

    for (list<A>::const_iterator itr3  = ll.begin(); itr3 != ll.end(); ++itr3) {
        cout << (*itr3).getVal() << endl;
    }
}

# 2  
Old 03-20-2012
Solved the problem myself, by adding the declaration outside the class and before main() like this.. Smilie
Code:
inline bool comp(const A&, const A&);

If we miss this, the function is not visible inside sort()

---------- Post updated 03-19-12 at 03:53 PM ---------- Previous update was 03-18-12 at 07:33 PM ----------

Can anyone help me to convert the above program to a template version? I am getting stuck in converting the function pointer 'comp', predicate function of sort() as a template. I am getting undefined reference.

---------- Post updated 03-20-12 at 11:24 AM ---------- Previous update was 03-19-12 at 03:53 PM ----------



In the following program why my std::find() algorithm is not able to search for the vector container element (7,9) though it is present there?
How to correct it?
Code:
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>

using std::vector;
using namespace std;

class CTest {
public:
     CTest(int _xx, int _yy) : x(_xx), y(_yy) {}
     int x, y;
};

int main() {
     vector<CTest*> vt;  // create an array of CMyClass object pointers

     cout << "initial capacity: " << vt.capacity() << endl; // Ans: 0
     vt.reserve(5); // causes reallocation manually, control invalidation of iterators
     cout << "present capacity: " << vt.capacity( ) << endl; // Ans: 5

     vt.push_back(new CTest(2, 4)); // dynamically add some elements, vector grow
     vt.insert(vt.begin(), new CTest(4, 6)); // stored in the index pos 0, replaces 2, 4

     vector<CTest*>::iterator itr1 = vt.begin() + 2; // stores in the index pos 1
     vt.insert(itr1, new CTest(6, 8));

     vt.push_back(new CTest(7, 9)); // pop_back() decreases size

     cout << "vector size: " << (int)vt.size() << endl; // Ans: vector size: 3
    /* always vector has 1 extra size */
     cout << "first x elem: " << vt[0]->x << endl; // Ans: 4
     cout << "first y elem: " << vt[0]->y << endl; // Ans: 6


     vector<CTest*>::iterator it; // stores in the index pos 1
     it = find(vt.begin(), vt.end(), new CTest(7, 9));
     if (it == vt.end())
         cout << "Could not find 7 in the vector" << endl;
     else
         cout << "Have found 7 in the vector" << endl;

     vector<CTest*>::iterator itr2 = vt.begin() + 2; // 2nd element iter
     delete *itr2;        // free the memory occupied by the 2nd element, here (2, 4)
     vt.erase(itr2);    // remove the 2nd element from the array, CTest (2, 4)

     vector<CTest*>::iterator itPos = vt.begin() /* + 0 */ ;
     for(; itPos < vt.end(); itPos++) {
         printf("Coordinates at %d is : (%d, %d)\n", (int)(itPos - vt.begin()) ,
                                                                       (*itPos)->x, (*itPos)->y);
         delete *itPos;  // deleting the memory for each and every element in the array
     }
     vt.clear();  // clear all elements from the array
}


Last edited by royalibrahim; 03-19-2012 at 02:24 AM..
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

C++, std:ofstream, and controlling an amplifiers mute function

Recently, I updated the unit I am running applications on with a new CODEC and amplifier; the older parts are EOL. There was a bug with the old setup. For some reason, even when a tone was not being generated, you could hear a noise emanating from the speaker when the LCD brightness was on a higher... (2 Replies)
Discussion started by: Circuits
2 Replies

2. Shell Programming and Scripting

sed q predicate doubt

Hi, Could anyone please explain me what the following command does? sed -ne "/\"$var\"/{=;q}" file (1 Reply)
Discussion started by: royalibrahim
1 Replies

3. Homework & Coursework Questions

Sort function -- My First Unix Homework!

1. The problem statement, all variables and given/known data: To sort a data 2. Relevant commands, code, scripts, algorithms: The data provided is saved in dummy.txt and provided in LIBSVM format, but I think this information is redundant.. +1 1:2 2:4 4:3.2 -1 2:2.1 2:2.1 ... (4 Replies)
Discussion started by: eeweepoh
4 Replies

4. AIX

Creating a pointer to std::istrstream is giving error

Hi I my code i have following statement std::istrstream *m_poIstream; when i compile with xlC_r verison 8 compiler throws following error : 1540-0063 (S) The text "*" is unexpected.* Any idea/pointers from nayeem khan (0 Replies)
Discussion started by: khan_069
0 Replies

5. Shell Programming and Scripting

redirecting std error

Hi, I use the following command make all > output-`date +%F-%H-%M-%S`.txt 2>&1 to invoke a MAKE process that takes some weeks to complete. The ouput is redirected to a text file. Now I prefix the above command with time to get time needed for completion of the MAKE process time make... (2 Replies)
Discussion started by: gkamendje
2 Replies

6. Programming

How to make a function friend to both base and derived class

Hi, I have a base class and derived a class from the base class, i want to print & read the data for the object created for the derived class,so i have overloaded both the << and >> operators and also have done the foward declaration. Below is the code snippet, #include <iostream> class... (3 Replies)
Discussion started by: ennstate
3 Replies

7. Programming

Sun Studio C++ - Getting error in linking std::ostream &std::ostream::operator<<(std:

Hello all Im using CC: Sun C++ 5.6 2004/07/15 and using the -library=stlport4 when linkning im getting The fallowing error : Undefined first referenced symbol in file std::ostream &std::ostream::operator<<(std::ios_base&(*)(std::ios_base&))... (0 Replies)
Discussion started by: umen
0 Replies

8. Shell Programming and Scripting

sort function in perl

Hi, here is my perl script.This script creates an array and is sorting it using the in-built sort function in perl. #!/usr/local/bin/perl my number=6; my @num_arr=(1,2,3,4,5); my @array=(23,"$number","Hello",2.345,@num_arr); #printing the array print... (2 Replies)
Discussion started by: DILEEP410
2 Replies

9. Shell Programming and Scripting

How to redirect std out and std err to same file

Hi I want both standard output and standard error of my command cmd to go to the same file log.txt. please let me know the best commandline to do this. Thanks (2 Replies)
Discussion started by: 0ktalmagik
2 Replies

10. Programming

sort function

do any one knows where i can find an implementation in c for the sort function (2 Replies)
Discussion started by: dbargo
2 Replies
Login or Register to Ask a Question