C++ :: Sorting Data Based On Some Metric - Function Pointer Syntax
Nov 20, 2014
I have a piece of code that sorts data based on some metric. The some metric is something I now want to make flexible so I can easily switch between and compare metrics. To do this, I want to pass the function to use as a parameter to the method that does the sorting (and other stuff). However, I'm having problems figuring out the syntax. Also, I think my [temporary] organization of code is violating a lot of basic code design principles.
To make the function pointer passable, I defined the "typename" in the header where the function is located (it is part of a struct, "Data"):
// Below the struct definition of Data
typedef double (Data::*CostF)(unsigned l, double W) const;
The two example functions I want to use are defined in that struct ("Data"):
// Inside the struct definition
inline double someExampleCost(unsigned l, double W) const {
// Returns some basic calculation
}
The function that uses it is part of a different class (that holds a reference to the first class, in case that matters; I feel like I'm doing something odd here, because I'm binding a member function in the definition/passing, but never referencing the object). It looks like this:
// Inside another class ("Foo")
inline void DoSomeStuff(double& ECost, double& TCost, CostF cost) {
// Irrelevant stuff here
std::sort(vector.begin(), vector.end(), [&](unsigned a, unsigned b){
return (*cost)(a, W) < (*cost)(b, W);
});
// More irrelevant stuff here
}
The error shown is "operand of "*" must be a pointer". If I remove the '*':
[code]return cost(A, W) < cost(b, W);
the error becomes: "expression must have a (pointer-to-)function type."
The call to this function is, currently, just in the main function, as I'm just testing before I wrap it into real code. It looks like this:
// In main
Foo bar; // Make an object of the struct that has the "sorting" function
CostF costFunction = &Data::someExampleCost;
// Bind to the Cost function bar.DoSomeStuff(varA, varB, costFunction);
This bit shows no errors by itself. So, my questions:
a) Clearly I'm missing the insight into Function Pointers. I'm comfortable with regular pointer stuff, but I can't wrap my head around FPs, partly due to the awkward syntax.
b) I'm very uncomfortable with the fact that I'm binding a member function of a class, but never try to reference an actual object of that class. This is probably a big part of why it's not working, but I can't seem to bind a function belonging to a specific object. I thought of doing
// In the main again
Data d; // Construct the object, which contains big lookup tables
Foo F(d); // Construct the object, which only holds a reference to a Data object
CostF costFunction = &d.someExampleCost; // Bind to the Cost function of that object
but that doesn't work ("a pointer to a bound function may only be used to call the function").
View 4 Replies
ADVERTISEMENT
Apr 1, 2014
I have a problem I am working on where I need to sort some data based on the values of a string of bits. The strings look like this,
010000001110000000
there are 18 bits, 1 means a feature is present, 0 means the feature is absent.
Each of these string has 4 on bits. I need to sort them such that I have the longest possible runs with 3 of the same on bits. It doesn't matter which 3 bits are on, I am just looking to order them in blocks with the longest possible runs. As a second step, the ordered blocks will be sorted by size large>small.
The following data is ordered like I need it to be.
Code:
// block 1, run of 12, keys 1,2,11 are identical (key 12 is also identical)
011000000001100000
011000000001100000
011000000001100000
011000000001100000
[Code] .....
This is the sort order that I am looking for. I need to be able to take a list of the bit strings in any particular order and sort them into the order above. The algorithm would need to recognize that there are 4 on keys and then look for groupings of three common on keys.
This is more of an algorithm question than one about specific implementation in code. I generally assume that most programming problems have been solved one way or another, so I don't know much about analyzing and manipulating strings of bits.
Is there a standard method for this kind of pattern recognition?
View 14 Replies
View Related
Dec 4, 2013
I have two classes, productListType and buyerListType, that are each basically linked lists. To create the linked list for an object of productListType, I successfully wrote a non-class function createProductList to read the product data from a text file. The class definition for buyerListType has a data member productBoughtRecord that is of type productListType to aggregate the details of the products purchased by a particular buyer during transactions. I decided to make productBoughtRecord a pointer since the contents of this data member would wax and wane over the course of several transactions, depending on the amount and frequency of payments made by the buyer. I have provided a rough sketch of the class below:
class buyerListType
{
public:
setCustomerInfo( ....., productListType* p);
.
.
.
private:
productListType* productBoughtRecord;
.
.
};
I'm similarly trying to write a non-class function createBuyerList to load the record of customers from a text file. How do I determine what the value of the formal parameter p in member function setCustomerInfo is, in order to be able to set the data member productBoughtRecord? take into consideration that an object of class buyerListType would have multiple buyers with varying amounts of products purchased.
View 11 Replies
View Related
Feb 16, 2013
I have a file which has records with 2 fields--one int and one float..what is the best way to sort it?
The sorting has to be based on the int field(the first field) (each time the program runs the file might end up with some hundreds of records).
View 13 Replies
View Related
Mar 26, 2013
knows if there is a ready made function in C++ to sort (numerically or alphabetically) multiple arrays based on a particular array?
i.e. Imagine you have multiple arrays or a multi-dimentional array containing data about users (name, age, etc.)
Is there a function that for example can sort it by name, and automatically shift the age so they still correspond to the correct user name?
View 2 Replies
View Related
Sep 1, 2014
New file_sorter.c:
#include <stdio.h>
#include <stdlib.h>
#include "sort.h"
#include <string.h>
[Code].....
My issue is now a segmentation fault in my sorting algorithm. In my assignment I was suppose to implement quick and insertion sort for the file, and organised strictly by ASCII values. We were allowed to look up generic algorithms for the sorts, but we have to convert them to comparing char arrays.
I haven't started trying to configure quick sort yet, but I'll supply the generic algorithm as well. keep in mind that the first line in the file contains the number of lines in the file. I'll try not to disappear this time!
sort.c :
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
[Code]....
View 4 Replies
View Related
Jan 18, 2014
I need to sort these students based on their test scores.
My biggest problem is with my sort function. I am not sure of the syntax to call the items the proper way. I also don't know how to call the function properly as I know that i can't pass a int to a struct. Also not sure about the z malloc. Just threw that one in there.
Code:
struct student{
int id;
int score;
};
void sort(struct student* students, int n){
/*Sort the n students based on their score*/
[Code] ....
View 5 Replies
View Related
Feb 13, 2013
I have a vector which contains vectors containing 7 integers each. I'd like to sort these vectors based on the value of the first integer (int IOT), in ascending order. I know this type of question can be found everywhere, but I'm lost as to why this doesn't compile.
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include <windows.h>
using namespace std;
class orders {
public:
int IOT; // Incoming Order Time
[Code] ....
View 7 Replies
View Related
Jul 6, 2014
error says "cannot convert 'int*' to 'int' in function main()
and also
type mismatch in parameter in function sort(int,int)
Heres the code:
#include<iostream.h>
#include<conio.h>
void main() {
void sort(int,int);
clrscr();
[Code] .....
View 11 Replies
View Related
Nov 26, 2013
I've been doing some practice programming challenges and I am currently making a temperature converter from Imperial to Metric.
My approach was to make it as simple as possible but it must display correctly and use decent I/O manipulations corresponding with how high the counter is.
This is what I have come up with, and everything seems to work fine for a base where I could possibly add more code to include user input, but before I go to that one step further I'd just like to know if the approaches I have taken to using iomanip is OK practice and I haven't done any serious no-nos, as I haven't seen any code from example videos that people make that includes this!
Here's the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
[Code] ....
The reason I added the IO manipulators is because I couldn't stand seeing everything not lining up, it looked very sloppy and unprofessional..
View 2 Replies
View Related
Feb 5, 2014
I'm familiar with function pointers as the method to pass a function as an argument to another function. However, I recently encountered some other syntax. I have seen in multiple times and in books,so I know it is probably not a syntax error. But I am not totally sure.
#include <iostream>
void Function1() { std::cout << "Function1"; }
void Function2(void aFunction()) { aFunction(); }
// make a param that describes the function the will be given
// as a param (return type, identifier,
[Code].....
View 4 Replies
View Related
Sep 11, 2012
i wrote a program on implementation of stacks using functions (data structures )...but i got expression syntax error in function main.....
View 2 Replies
View Related
Aug 19, 2014
What I want to do is simple, however I can not find a way to do it in c++ and I don't know for sure that it is possible. I want to create a function that creates a simple short-hand for printf(x); Such as:
void echo(x){
printf(x);
}
But when I call the function:
echo "hi";//I want it to look like this
//instead of:
echo("hi");// like this.
View 2 Replies
View Related
Jan 8, 2014
I wrote this program and compiled in turboc, but it gets error"declaration syntax error" .
Code:
#include <stdio.h>
int main()
int isprime(int n)
{
if(n<2)
return 0;
[Code] ....
View 5 Replies
View Related
Nov 29, 2014
I have a class called Book and I am trying to create a dynamic pointer based array of the class. When I try to run the program I keep getting the error: pointer being freed was not allocated at the line of code that says "delete [] A;". I am using Xcode to run the program.
Book *changeArraySize(Book *A, int &size, double factor) {
int i;
int newsize = size*factor;
Book *A2 = new Book[newsize];
[Code] ....
View 7 Replies
View Related
Nov 29, 2014
I'm trying to read a "pointer-based" maze .txt. The first letter in each row corresponds to the room letter...then the letters that follow are North node, East node, South node, and West node respectively. The asterisk indicates an empty room or not a valid option.
Here is what I have come up with, what is happening is after the file is parsed by read_maze it is calling my is_empty function indicating that there is no maze because it doesn't go into the else statement here.
I've attached a sample input file:
maze.txt (130bytes)
Number of downloads: 19
We can't assume the rooms will be in order alphabetically A - Z, We are expecting a maximum of 12 rooms and there is a space between each letter or asterisk.
void Maze::read_maze(string FileName){
string line;
ifstream inStream;
inStream.open(FileName.c_str());
int test = inStream.peek();
int i = 0;
if (!(inStream.fail())){
while (!inStream.eof() && test != EOF){
[code]....
View 5 Replies
View Related
Nov 8, 2013
In my project, GreedyKnap::calKnap(int nItem, int nCapacity, float fWeights, float fProfits);
This function include two array member pass as parameter. how can i do this?
View 1 Replies
View Related
Aug 6, 2012
My code compiled well(After long Messing up with my head). But, i still not satisfied of my output as i expected. My code ought to sort the object of person comparing their salary. But, its not.
Code:
#include <iostream>
#include <string>
using namespace std;
class person {
protected :
string name;
float salary;
[Code] ....
It doesn't sort the object of class person rather than it prints out the stored value as it is.
View 3 Replies
View Related
Dec 23, 2014
I have a area in my Project where i need to display a title and content in two text boxes. The Data base tables are:
ID | Title | Content
This is what I have so far, I know I am on the right track, I just cant figure out how to get each box to display based on the ID.
private void frmMain_Load(object sender, EventArgs e){
try {
string connStr = ConfigurationManager.ConnectionStrings["sdcAssistDB"].ConnectionString;
OleDbConnection dbConn = new OleDbConnection(connStr);
dbConn.Open();
[Code] ....
View 3 Replies
View Related
Mar 14, 2013
I'm trying to call a function via a function pointer, and this function pointer is inside a structure. The structure is being referenced via a structure pointer.
Code:
position = hash->(*funcHash)(idNmbr);
The function will return an int, which is what position is a type of. When I compile this code,
I get the error: error: expected identifier before ( token.
Is my syntax wrong? I'm not sure what would be throwing this error.
View 3 Replies
View Related
Apr 24, 2013
I want to create a binary file based on some hex data :
Ex Input Hex :54313032202020303030
Out put like :6
View 2 Replies
View Related
Apr 23, 2013
Generate a binary ascii characters(weird character ) based on Hex:54313032202020303030 data in C++
View 3 Replies
View Related
Feb 7, 2014
Player is given choice of x number of Races This choice changes the player's base stats. Then player is given a choice of x number of Classes (archer, warrior, etc.) This choice determines how the player's stats will change upon leveling up.
#include <cmath>
#include <iostream>
#include <ctime>
[Code]....
View 7 Replies
View Related
Sep 27, 2013
how to stop outputting data based on a user input. The text file is as follows:
1. a
2. b
3. c
and the code I'm using is as follows:
int main (){
string line;
int search;
cout << "Enter a number from 1-3" << endl;
cin >> search;
search++;
ifstream myfile ("example.txt");
[Code]...
What I want to do is to just output number 1 (the whole line) if the user enters number 1. However, I get an error on the second condition w/c is the "&& line!= search"
View 1 Replies
View Related
Dec 22, 2014
I'm trying to make a Quiz program based on C++'s Data File Handling capablities. I've attached the code in .txt file and I wonder why I'm getting the error identifier bScience cannot have a type qualifier?
Attached Files QuizPro.txt (9.6 KB)
View 7 Replies
View Related
Apr 22, 2012
Ok I'm trying to create matrix of data that I can add values to based on a reading that I will get from a DVM. I'm using a 3d vector to do this. I need to keep track of the serial number, the day and within day I need to take two readings at different temps, this will continue for 7 days.
The rows of my 3d vector will be the days, the colums will be the serial numbers the depth will be the reading at the different temps.
What I need to do is compare the first element (days) and when it is greater then or equal to 4 I will perform calculations of the readings. So all I want to do is compare the first element of the vector, How do I do this?
Here is what I got
Code:
#include <vector>
typedef std::vector<double> Double1D;
typedef std::vector<Double1D> Double2D;
typedef std::vector<Double2D> Double3D;
#define HEIGHT 5
#define WIDTH 3
[Code]....
View 7 Replies
View Related