C++ :: Generalized Sort Function Using Lambda Functions
Jan 15, 2014
How to improve my customSort function. It is to accept a lambda function as parameter which customizes your sort in any special way you want.
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
#include <functional>
enum personType {teacher, student, baby};
[Code] ....
For example, std::vector<Person> people = {Mark, MrMac, Lola, MsWhite, Cindy, Zainab, Mikey, Fred, Zolal} is to be sorted so that teachers will be placed first, then students, and then babies, but with the exception that people with names starting with Z be placed before anyone else, followed by people with age equal to 8. All this is set up by the ordered list:
person.name.at(0) == 'Z',
person.age == 8,
person.type == teacher,
person.type == student,
person.type == baby
So the output gives
Zolal
Zainab (baby)
Cindy
Ms. White
Mr. Mac
Fred
Mark
Mikey (baby)
Lola (baby)
Teachers are supposed to be placed before students, which in turn placed before babies, but Cindy's age is 8, and so is placed before the teachers, and Zolal and Zainab start with Z, so is placed before her. So far so good, but now I want the further sorting result that all people within their subcategories be sorted in their own way, e.g. Zainab should come before Zolal alphabetically, Ms. White should precede Mr. Mac because she is younger, etc... How do I further generalize my customSort function so it carries out those further criteria as well?
View 9 Replies
ADVERTISEMENT
Jul 1, 2014
I am trying to write a function that extracts chunks of numbers from a stream (ie if i had "ui33ui24ui23hjdwejf" it would extract the chunk 33), and its finished, but it wont compile. errors here: [URL] ...... its only one line in an include file, but im stumped. anyways, this is the most updated version of the code: [URL] .....
View 1 Replies
View Related
Mar 6, 2014
I have this method called "walk" and what it's supposed to do is, walk through a bunch of triangles one step at a time (the're all connected [not to each other, but in a mesh]).
To do so, I need to perform a containment test.
Normally, I guess I'd just write a separate function but what if I wanted to be weird and write my inclusion test as a lambda in my walk method? Literally the only function that needs this code is my walk() procedure and I need to call the test an arbitrary amount of times.
Is this frowned upon? Would this be the jarring type of code I've been warned about? Or should I just say yolo and do what I want?
View 4 Replies
View Related
May 13, 2014
I am trying to realize a simple code with thread and lambda function.
My goal is to swap 2 variable . I launch 2 thread,
The first:
Put his value in a shared variable and notify it .
wait until an event on a condition variable occur.
read from shared value .
The second wait until an event on a condition variable occur.
Wake up
read from shared value .
Put his value in a shared variable and notify it.
This is the code
thread t1([&p1]()->void{
m.lock();
nt++;
if(nt==1) {
//first thread
unique_lock<mutex> u1(m); ***
[Code] .....
Why it say error "abort() has been called " on the istr ***
View 2 Replies
View Related
Aug 19, 2013
Example radix sort function to sort an array of 64 bit unsigned integers. To allow for variable bin sizes, the array is scanned one time to create a matrix of 8 histograms of 256 counts each, corresponding to the number of instances of each possible 8 bit value in the 8 bytes of each integer, and the histograms are then converted into indices by summing the histograms counts. Then a radix sort is performed using the matrix of indices, post incrementing each index as it is used.
Code:
typedef unsigned long long UI64;
typedef unsigned long long *PUI64;
PUI64 RadixSort(PUI64 pData, PUI64 pTemp, size_t count) {
size_t mIndex[8][256] = {0};
/* index matrix */
PUI64 pDst, pSrc, pTmp;
size_t i,j,m,n;
UI64 u;
[Code]....
View 9 Replies
View Related
Mar 31, 2015
I can write code that can sort arrays with Bubble, Selection and Insertion algorithms but I'm not sure how to have them be called and return a value 3 different times with 3 different sizes. For example, I need it to return 10, 100 and 1000 but I'm stuck.
#include <stdio.h>
void selectionSort (int list[], int last);
int main()
[Code].....
View 14 Replies
View Related
Mar 22, 2013
how to sort a 1D array using function sort().but if i have a 2D array how do i sort only 1 row of it (or column)?
View 2 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
Mar 31, 2015
I get the following error:
Cannot convert lambda expression to type system delegate because it's not a delegate type (on invoke).
The Second error is: Client.PrivateChat.txtReceive is inaccessible due to its protection level..
private PrivateChat pChat;
private void client_Received(Client sender, byte[] data) {
this.Invoke(() =>
{
for (int i = 0; i < clientList.Items.Count; i++) {
var client = clientList.Items[i].Tag as Client;
if (client == null || client.Ip != sender.Ip) continue;
[Code] .....
View 4 Replies
View Related
Feb 1, 2013
I'm trying to expand a template + argument parameter list inside a lambda function like this:
template <typename Class, typename ...Args>
static void create(Args ...args) {
// Perform pre-thread creation work.
std::thread([=]()
[Code] ....
But this does not work:
The compiler error is "error: parameter packs not expanded with ‘...’:|"
However, when I do the following:
template <typename Class, typename ...Args>
static void create(Args ...args) {
// Pre-thread work.
auto tthr = [](Args ...ar) -> void {
[Code] ....
It works just fine. That shows that lambda threads are able to take variadic arguments...
So here is my question; what is the correct capture clause for capturing the variadic object correctly?
View 3 Replies
View Related
Dec 5, 2014
i have stuck in a join and i cant figure out where the problem is, i have those tables
public class Themes
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[Code].....
View 12 Replies
View Related
Feb 17, 2014
I have a class which upon construction has a part which should be executed when the constructor has finished "enough" to make the call valid.
Take the following simplified class example (the actual problem is much more elaborate):
Code:
#include <functional>
class base {
public:
base(int i, std::function<void()> func) : mi(i)
[code]....
Explicitely creating a derived class allows me to properly implement the lambda to call a member of the class.
I can't seem to figure out how to do this for an explicit instantiation of the base class.
Can this be done ? Or is this a shortcoming of VS2012 or something the standard doesn't handle ?
View 12 Replies
View Related
May 30, 2013
I've was trying out a function template to automatically get the type of a lambda, but it seems that it won't compile
I've tried two different ways:
1.
template<class HASHER>
auto make_unordered_map(size_t bucketCount, HASHER const && hf)
-> unordered_map<string const, HASHER>&& {
return unordered_map<string const, int, HASHER>(bucketCount, hf);
} auto x = make_unordered_map(1, [](string const& key)->size_t { return key[0]; });
2.
template<class HASHER>
auto make_unordered_map(size_t bucketCount, HASHER const && hf2)
-> unordered_map<string const, int, decltype(hf2)> {
return unordered_map<string const, int, decltype(hf2)>(bucketCount, hf2);
} auto x = make_unordered_map(1, [](string const& key)->size_t { return key[0]; });
The test code are located here:
1. [URL] ....
2. [URL] ....
They are both based on the code that is stated to work in those examples. I.e.:
auto hf = [](string const& key)->size_t { return key[0]; };
unordered_map<string const, int, decltype(hf)> m (1, hf);
View 13 Replies
View Related
May 24, 2013
In this code:
// Ex10_15.cpp Using lambda expressions
#include <algorithm>
#include <iostream>
#include <iomanip>
[code].....
The lambda accepts no arguments, but it accesses increment by value and current by reference, the latter being used to store the next value to be set. This lambda has the side effect that current will be updated when generate is finished. The following lambda expression is similar, but without the side effect:
[=]()mutable->T{T result(current);
current += increment;
return result;}
"
I dont exactly understand what side affect it is talking about. Wouldn't you want generate to update current? I understand how the second code fixes it though, just takes everything in the enclosing scope by value.
View 2 Replies
View Related
Feb 28, 2013
Im suppose to make a "poor mans" variation to the Sort function built into unix. The program is suppose to read in a file and sort the contents of the file. So its a variation of the Unix Sort feature. I have remade the readLine function we were provided so that it doesnt use fgets. where to go from here, Not sure on how to make a sort function. Here are the reqirements of the program:
Code:
• Re-implement the readLine() function so that it no longer makes use of fgets(). Instead,
process the input on a given line character-by-character.
• Provide code which will create a data structure similar to argv to hold all of the words to be sorted. Use malloc() to ensure that each entry has just the required number of bytes needed to store the words. The final entry in your array should be the NULL pointer.
• Implement a sort() function which will rearrange the words in sorted order. To swap two words in your array, note that only a pair of pointers need to move. The strings themselves, once established, will never move. Heres what i have:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 1000 /* maximum number of reminders */
#define WORD_LENGTH 10 /* max length of reminder message */
[code]....
View 9 Replies
View Related
Oct 30, 2014
I need to include validation to only accept numbers and to only the last four odd numbers in the table.
Code:
#include <stdio.h>void main() {
int upper, range, i;
printf("Enter an integer to find multiplication table: ");
scanf("%d",&upper);
[Code].....
View 3 Replies
View Related
Apr 30, 2013
I need to write a standalone sort function, which will take a linked list parameter and sorts it. The function is included in the main list class as friend class: Code: friend void sort (UList<T>&) I need to submit separate SortIS.h file for insertion sort. Here is my code:
Code:
#include <iostream>
template <class T>
void SortIS(UList<T>& list)
{
T temp;
for (int i=1; i<list.size(); i++)
{
temp = list[i];
[Code]...
But the teacher said it didn't compile returning an error: "undefined reference to `void". What I am missing here?
View 6 Replies
View Related
Mar 6, 2015
I have this code(homework) i've been working on for several days i couldn't fix this error.
Question is: to write a sort program in c . Ineed to ask user for how many numbers to be sorted(n) ask again for values. The approach of sort is this:
1- store n in temporary var (temp)
2- search for largest number in array (0 until temp-1)
3- switch the fied that store largest with field indexed by (temp-1)
4- temp-- (decrement)
5- repeat steps 2 to 4 until temp is 1
the program then prints the numbers of array on screen in one line. I also should use a function getMax(int *list , int n) that determines largest value and returns its location in that array
list : is the array
n: number of elements
Code:
#include<stdio.h>
int getMax(int *list, int n); //definition of getMax function
int main(void) {
int n,i;
[Code] .....
so i tried to sort this array
Code:
input 2 7 9 4 3 1 6 5
The out put should be : 9 7 6 5 4 3 2 1
instead it prints : 7 9 2 4 3 1 6
View 11 Replies
View Related
Jan 19, 2014
i am currently using a comparator function in STL map for sorting date of string data type in ascending value. My dates are in this format for e.g. 15OCT1990, 13SEP1980 and etc. I am using substring to split up the string so that i can compare day, month, year separately. Right now i have problem comparing the month portion because alphabetically "FEB" comes before "JAN".How can I make a fixed substring position of (2,3) which is my month value to accept that string value of JAN comes before FEB,AUG,DEC for e.g?
struct sortMapDaily: public std::binary_function <bool, std::string, std::string>
{
bool operator() (const std::string& lhs, const std::string& rhs)
{
[Code].....
View 5 Replies
View Related
Mar 9, 2013
I'm passing an array into this function and it's taking the item at index 0 and replacing the rest of the array with it.
Code:
void generic_sort (void *arg, size_t num, size_t size, int (*cmpfnc) (const void *, const void *)) {
for (int i = 1; i < (int)num; ++i) {
int j = i;
char *tmp_address = malloc (sizeof (arg));
tmp_address = (char *)arg + j * size;
[Code] ....
View 13 Replies
View Related
Jan 15, 2015
This program I'm working on accepts an array size from the user, prompts the user to store that many integers, sorts them from smallest to largest, and then searches for duplicates with a simple for loop. The ultimate goal of the assignment was to display duplicates in an array, and the rest of the functions are just how I decided to reach that goal.
Anyway, my program crashes if I choose an array size larger than 7. It sorts and displays duplicates perfectly with 7 or fewer arguments.
The exact moment it crashes is after I enter the final value it prompts me for, so it appears my inputsize() function and my inputarray() function are working, and the error may be in the arrsort() function. Code is below:
Code:
#include <stdio.h>
int funcinputsize(int);
void funcinputarray(int [], int size);
void funcarrsort(int [], int size);
void funcdupe(int [], int size);
[Code] ...
View 4 Replies
View Related
Jan 14, 2014
I need to write a code (in C99). The programe receives an input number (integer) 'n' and then a matrix sized n*n (matrix[n][n]), all numbers are integers. We're supposed to define the matrix's size with malloc. Now the program needs to sort the lines of the matrix (the number in each line), in a single function (!) this way:
even line index (0,2,4,6...): from small to big.
odds line index (1,3,5...): from big to small.
and then print it.
*note: first line is indexed 0, second line is 1, etc.
I was thinking to sort it with bubblesort function with the following if:
if(i%2==1)
do odds sorting.
else
do even sorting.
when i is the index of the row.
my problem is defining the malloc and how do I send the matrix to sorting.If needed I will attach my current (not so good (completly awful)) code and functions as well as an example of what the prog. supposed to do.
View 13 Replies
View Related
Oct 7, 2014
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
const int s = 12, p = 6;
int x[s][p];
[Code] ....
Names: P1 P2 P3 P4 P5 P6 AVER.
EVIKE 41 85 72 38 80 69 64.17
KKASV 65 68 96 22 49 67 71.86
YCXFX 51 61 63 87 66 24 70.64
FADPO 80 83 71 60 64 52 80.11
OEJUV 90 60 49 31 23 99 72.02
POEYL 94 11 25 24 51 15 48.67
VRVIP 13 39 67 97 19 76 59.94
QNQRQ 12 33 99 18 92 35 58.16
OOVAO 74 0 95 71 39 33 61.69
NCBXC 39 32 37 45 57 71 57.12
ATXDK 95 5 71 24 86 8 57.69
IXJSW 51 54 74 24 75 70 67.61
AVER. 58.75 49.15 72.35 51.11 62.68 56.81
1: Sort Alphabetically
2: Sort Grades Increasing Order (Student)
3: Sort Grades Increasing Order (Project)
4: End Program Enter choice: 2
Names: P1 P2 P3 P4 P5 P6 AVER.
XXZRZ 41 72 38 80 69 65 60.83
OKETL 68 85 22 49 67 51 67.14
GZQRC 61 63 87 66 24 80 74.69
OJWAY 83 71 60 64 52 90 82.45
PSAJL 60 49 31 23 96 94 72.57
AOVLZ 11 25 24 51 15 13 35.26
CPWSR 39 67 97 19 76 12 57.54
IZCOB 33 99 18 92 35 74 68.09
IJTVD 0 95 71 39 33 39 57.52
LDVGY 32 37 45 57 71 95 65.75
MBORX 5 71 24 86 8 51 51.79
XOHGM 54 74 24 75 70 0 58.13
AVER. 40.58 70.72 50.98 62.66 56.56 60.05
1: Sort Alphabetically
2: Sort Grades Increasing Order (Student)
3: Sort Grades Increasing Order (Project)
4: End Program Enter choice:
Why my sort is not working. Also, I want to keep the same random numbers for the continuation of the program, I don't want new randomized values when I display the table.
View 4 Replies
View Related
Oct 7, 2013
I'm having trouble getting my sort function to work,
void Linkedlist::sort(int num)
{
node *q;
node *a;
int input=num;
[Code].....
I get a crash and I've narrowed it down to the last if statement. Also this function is meant to handle new members after 1 member has been added.
View 7 Replies
View Related
Apr 7, 2012
I Need to write a function using C wherein I should do the following:
(i) The function will receive a string in a character pointer
(ii) This string will adhere to the following structure:
"Kentucky+New York+Arizona+Nevada"
The number of states can differ from 4 to 50
The delimiter between States can differ from '+' to ',', hence I would like to pass the delimiter to the function.
(iii) This string should then be sorted alphabetically from left to right.
The above example would then become: "Arizona+Kentucky+Nevada+New York"
(iv) This string needs to be returned from the function using a character pointer.
View 3 Replies
View Related
Dec 2, 2014
The Problem You are part of a company writing a spreadsheet program. As you know, spreadsheets can be sorted on any column. You're part of the project is to write one binary tree function to sort the data [Hint: use different fields when inserting nodes in the tree.] and a second function to list it in either an ascending or descending sequence. [Note: Each of these functions may actually need to be a set of related functions.]
For sample data you will have a disk file containing information about Shakespeare's plays. Your first function should create a tree based on the sort selected by the user and the second function to display the data in the sequence selected by the user. Regardless of the column being sorted, data in individual records always be displayed in the same line of the output.
Input : Each record will contain the following information: First Performed 9 characters Printed 5 characters Title 26 characters Type 7 characters
Output : Tabular output should be aligned in columns with two spaces between each. All columns should have headings. It should be sorted on the column specified by the user.
Example (This sample data provided so you can test your program.) If the data is:
1595-96 1600 A Midsummer Night's Dream Comedy
1594-95 1623 Two Gentlemen of Verona Comedy
1596-97 1623 King John History
1597-98 1598 Henry IV, Part 1 History
1611-12 1623 The Tempest Comedy
1602-03 1623 All's Well That Ends Well Comedy
[Code]...
Source: [URL]...
Possible outputs are
1 - for a sort by title: First
Performed Printed Title Type
--------- ------- -------------------------- -------
1595-96 1600 A Midsummer Night's Dream Comedy
1602-03 1623 All's Well That Ends Well Comedy
1606-07 1623 Antony and Cleopatra Tragedy
1599-1600 1623 As You Like It Comedy
[Code]....
2 - for a sort by first performed: First
Performed Printed Title Type
--------- ------- -------------------------- -------
1590-91 1594? Henry VI, Part 2 History
1590-91 1594? Henry VI, Part 3 History
1591-92 1623 Henry VI, Part 1 History
1592-93 1623 Comedy of Errors Comedy
1592-93 1597 Richard III History
[Code]....
View 1 Replies
View Related