Ich möchte eine Funktion implementieren, die als MATLAB sort() fungiert. Ich habe eine Struktur und eine Funktionsvorlage in einer Kopfdatei wie unten definiert.Funktionsvorlage als Funktion Argument
template<typename T_val> struct SORT_DATA
{
T_val value; //
int index;
};
template<typename T_var>
bool ccmp(SORT_DATA<T_var> & var_a, SORT_DATA<T_var> & var_b)
{
return var_a.value < var_b.value;
}
In main(), verwende ich eine Struktur variabel und passieren die CCMP() als Argument für C++ sort(), wie unten.
//SORT_DATA<double> * data1 = new SORT_DATA<double>[15];
SORT_DATA<double> data1[15];
double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6};
for(int i=0; i<15; i++)
{
data1[i].value = tmp_data[i];
data1[i].index = i;
}
//sort(data1, data1+15, ccmp);
for(int i=0; i<15; i++)
std::cout<<setw(5)<<data1[i].value<<" ";
std::cout<<std::endl;
for(int i=0; i<15; i++)
std::cout<<setw(5)<<data1[i].index<<" ";
Ich habe mehrere Probleme: 1. Es scheint, dass der Speicher für die Strukturvariablen zuzuweisen gescheitert war. 2. Ich habe eine Fehlermeldung von VS2010 erhalten, die besagt, dass die Funktionsvorlage nicht als Funktionsargument verwendet werden kann.
#pragma once
#include <iostream>
#include <iomanip>
#include <algorithm>
#include "customizedalg.h" // This is simply the declaration of the struct and bool cmp().
using namespace std;
int main(int argc, char ** argv)
{
SORT_DATA<double> * data1 = new SORT_DATA<double>[15];
//SORT_DATA<double> data1[15];
double tmp_data[15] = {25, 23, 1, 32, 0, 43, 98, 8, 7, 11, 34, 52, 32, -53, 6};
for(int i=0; i<15; i++)
{
data1[i].value = tmp_data[i];
data1[i].index = i;
}
sort(data1, data1+15, ccmp<double>);
for(int i=0; i<15; i++)
std::cout<<setw(5)<<data1[i].value<<" ";
std::cout<<std::endl;
for(int i=0; i<15; i++)
std::cout<<setw(5)<<data1[i].index<<" ";
std::cout<<std::endl;
std::cin.ignore();
return 0;
}
'for (int i = 0; i ++; i <15) 'so sollte eine for-Schleife nicht aussehen –
Bitte geben Sie eine [mcve] an. Wenn Sie eine Fehlermeldung über eine bestimmte Zeile im Code haben, markieren Sie diese Zeile eindeutig –
@PiotrSkotnicki Danke Piotr. Es ist lange her, dass ich C++ nicht benutzt habe. Das ist ... MATLAB-Stil. Jetzt kann es Werte ausgeben, aber die zweite benötigt noch Hilfe. – user18441