can positions of max n elements (the equal max elements) using predefined function in stl?
a solution thought of is:
vector<int> maxn(vector<int> original){ vector<int> result; auto pt = max_element(original.begin(),original.end()); int max = *pt; while(*pt == max){ result.push_back(distance(original.begin(),pt)); *pt = 0;//assumed elements in original greater 0 pt = max_element(original.begin(),original.end()); } return result; }
there must more elegant way this.
once have found max element, make linear pass on vector find matching elements. setting 0 not needed when doing way. original vector being passed value, setting 0 not being seen caller. makes clear implementation:
vector<int> maxn(vector<int> original){ vector<int> result; if (original.empty()) return result; const int max = *(max_element(original.begin(), original.end())); (int = 0; < original.size(); ++i) { if (original[i] == max) result.push_back(i); } return result; }
it more importatnt implement clear , maintainable code attempt extract maximal reuse c++ library.
if goal not use explicit loop on passed in original vector, use standard c++ template algorithm, recommend creating helper iterator recover index.
struct indexer { int i_; indexer (int = 0) : i_(i) {} indexer & operator ++ () { ++i_; return *this; } indexer operator ++ (int) { ++i_; return i_ - 1; } int operator * () const { return i_; } bool operator != (indexer rhs) const { return i_ != rhs.i_; } //... whatever else required copy_if };
then, can invoke copy_if
simple lambda , insert iterator:
copy_if(indexer(), indexer(original.size()), back_inserter(result), [&](int i) -> bool { return original[i] == max; });
however, more obscure straightforward loop presented above.
Comments
Post a Comment