Попробуйте awk с несколькими разделителями
$ echo "Min/Max Inference Time : 70 ms / 290 ms" | \
awk -F"[/ ]+" ' { print $1, ":", $(NF-3); print $2,":",$(NF-1) } '
Min : 70
Max : 290
$
РЕДАКТ. EDIT2: с Perl, $ awk -F: -v OFS=":" ' { if(/\//) { split($1,a,"[ /]+"); split($2,b,"ms|/"); print a[1],b[1]; print a[2],b[3] } else { print } }' scores.csv
Min: 70
Max: 290
Average Inference Time : 90 ms
$
$ perl -lne ' /(.+?)\/(.+?)\s+.+?(\d+).+?(\d+)/ ? print $1,": ",$3,"\n",$2,": ",$4 : print ' scores.csv
Min: 70
Max: 290
Average Inference Time : 90 ms
$
возможно, std::lower_bound
std::upper_bound
поможет Вам.
Вот универсальное использование решения std::lower_bound
:
template <typename BidirectionalIterator, typename T>
BidirectionalIterator getClosest(BidirectionalIterator first,
BidirectionalIterator last,
const T & value)
{
BidirectionalIterator before = std::lower_bound(first, last, value);
if (before == first) return first;
if (before == last) return --last; // iterator must be bidirectional
BidirectionalIterator after = before;
--before;
return (*after - value) < (value - *before) ? after : before;
}
Вы заметите, что я использовал Двунаправленные Итераторы, подразумевая, что функция может только работать с итераторами, которые могут быть и увеличены и постепенно уменьшены. Лучшая реализация только наложила бы Входное понятие Итераторов, но для этой проблемы это должно быть достаточно хорошо.
Так как Вы хотите индекс и не итератор, можно записать немного функции помощника:
template <typename BidirectionalIterator, typename T>
std::size_t getClosestIndex(BidirectionalIterator first,
BidirectionalIterator last,
const T & value)
{
return std::distance(first, getClosest(first, last, value));
}
И теперь Вы заканчиваете с кодом как это:
const int ARRAY_LENGTH = 5;
double myarray[ARRAY_LENGTH] = { 1.0, 1.2, 1.4. 1.5, 1.9 };
int getPositionOfLevel(double level)
{
return getClosestIndex(myarray, myarray + ARRAY_LENGTH, level);
}
который дает следующие результаты:
level | index
0.1 | 0
1.4 | 2
1.6 | 3
1.8 | 4
2.0 | 4
Массив, как гарантируют, будет в порядке возрастания? Если так, дайте std::lower_bound
взгляд.
Я думаю, что мой пример делает точно, что Вы хотите:
(Я использую станд.:: min_element и функтор)
#include <algorithm>
#include <cmath>
const int ARRAY_LENGTH = 5;
double myarray[ARRAY_LENGTH] = { 1.0, 1.2, 1.4, 1.5, 1.9 };
struct CompareDistanceFromLevel
{
CompareDistanceFromLevel(double cLevel) : level(cLevel) {}
bool operator()(double lhs, double rhs)
{
return std::abs(level - lhs) < std::abs(level - rhs);
}
private:
double level;
};
size_t getPositionOfLevel(double level)
{
double *result;
result = std::min_element(myarray, myarray+ARRAY_LENGTH, CompareDistanceFromLevel(level));
return (result-myarray); // returns the index
}
#include "stdafx.h"
#include <limits>
using namespace std;
static const int array_len = 5;
double myarray[array_len] = { 1.0, 1.2, 1.4, 1.5, 1.9 };
int approx_search(const double val)
{
double min_val = numeric_limits<double>::max();
int index = 0;
for(int i=0;i<array_len;++i)
{
double diff = abs(myarray[i] - val);
if(diff<min_val)
{
min_val = diff;
index = i;
}
}
return index;
}
int _tmain(int argc, _TCHAR* argv[])
{
printf("approximate %d\n",approx_search(1.6));
printf("approximate %d\n",approx_search(1.7996));
printf("approximate %d\n",approx_search(1.4996));
printf("approximate %d\n",approx_search(0.0002));
return 0;
}