I'm trying to use std::min_element and std::max_element to return the minimum and maximum elements in a vector of doubles. My compiler doesn't like how I'm currently trying to use them, and I don't understand the error message. I could of course write my own procedure to find the minimum and maximum, but I'd like to understand how to use the functions.
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char** argv) {
double cLower, cUpper;
vector<double> C;
// Code to insert values in C is not shown here
cLower = min_element(C.begin(), C.end());
cUpper = max_element(C.begin(), C.end());
return 0;
}
Here is the compiler error:
../MIXD.cpp:84: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
../MIXD.cpp:85: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
What am I doing wrong?
min_element and max_element return iterators, not values. So you need *min_element... and *max_element....
As others have said, std::max_element() and std::min_element() return iterators, which need to be dereferenced to obtain the value.
The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C++11 for brevity):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
This yields:
Max element is 5 at position 4
min element is 1 at position 0
Note:
Using std::minmax_element() as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9 since...
If several elements are equivalent to the largest element, the iterator to the last such element is returned.
min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:
cLower = *min_element(C.begin(), C.end());
Related
I am trying to understand why the map changes the first element position to the fourth. When I print the map, the first added position goes to the fourth one.
#include <stdio.h>
#include <stdlib.h>
#include <map>
#include <iostream>
typedef std::map<double, unsigned int> A;
double fRand(double fMin, double fMax)
{
double f = (double)rand() / RAND_MAX;
return fMin + f * (fMax - fMin);
}
Here is the main function:
int main ()
{
int i, number;
double c;
number = 5;
A a;
for( i = 0 ; i < number ; i++ )
{
c = fRand(1, 9);
a[c];
std::cout << c<<"\n";
}
for(std::map<double, unsigned int>::const_iterator it = a.begin();
it != a.end(); ++it)
{
std::cout << it->first << " -> "<< it->second <<"\n";
}
return(0);
}
Answer : The first Element went to the fourth position
**7.7215** first
4.15506
7.26479
7.38752
8.29318
4.15506 -> 0
7.26479 -> 0
7.38752 -> 0
**7.7215 -> 0** fourth
8.29318 -> 0
std::map does manage the ordering of the elements according to the keys <, or a custom comparator. Thats actually the main feature of a std::map. If you don't want that then don't use a std::map. If you want to keep the elements in order of insertion you could use a std::vector< std::pair< double, unsigned int>> instead. Just beware of the different complexity guarantees you get from the different containers for eg insertion, lookup, iteration, removal, etc.
std::map stores elements in order of the key. It so happens that you generated numbers in a nearly ascending order.
lower_bound function of C++ returns a pointer to the first array element that is at least equal to x (the third argument passed to the function). Here is the code which I compiled online using an online compiler for C++.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(2);
cout<<lower_bound(v.begin(),v.end(),2)-v.begin()<<endl;
return 0;
}
Output I expected was 1 but actual result says 3. Can someone please explain why this is so?
https://en.cppreference.com/w/cpp/algorithm/lower_bound
The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.
This order:
v.push_back(1);
v.push_back(2);
v.push_back(1);
v.push_back(2);
does not fulfill that criterion.
The range [first, last) must be partitioned with respect to the expression element < value or comp(element, value), i.e., all elements for which the expression is true must precede all elements for which the expression is false. A fully-sorted range meets this criterion.
https://en.cppreference.com/w/cpp/algorithm/lower_bound
Your input does not satisfy this requirement (not sorted), therefore the output is undefined.
std::lower_bound
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
std::sort (v.begin(), v.end()); is important, the number list has to be in ascend order.
I have a vector of real values, sorted by increasing order.
These values can be within the range [0, 1]. Then I pick a value x within this range and I need to find which is the index of the smaller value greater or equal to x.
I can solve this problem by iterating over the whole array:
vector<double> values;
double x;
for (auto val : values)
{
if (x <= values)
{
// found
break;
}
}
Is there a faster way to get the same result? I was thinking about a binary search, but how to implement it?
Use std::lower_bound:
#include <iterator>
#include <algorithm>
std::distance(begin(values)
, std::lower_bound(begin(values), end(values), x));
If the item doesn't exist, it'll give you an index one greater than that of the last element.
DEMO
The function lower_bound might meet your demand,and you can use it like below:
iter =lower_bound(values.begin(),values.end(),x);
You can use operator[] to directly access the items in a vector just like an array, instead of using an iterator to start from the begin. I assume you already know Binary Search. Implement it in an array is something you can find anywhere, so I won't explain it to you here. Just treat the vector as an array.
You know SO is not a site that you request someone to write you the code, so take this example of std::binary_search and make your way:
// binary_search example
#include <iostream> // std::cout
#include <algorithm> // std::binary_search, std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
int main () {
int myints[] = {1,2,3,4,5,4,3,2,1};
std::vector<int> v(myints,myints+9); // 1 2 3 4 5 4 3 2 1
// using default comparison:
std::sort (v.begin(), v.end());
std::cout << "looking for a 3... ";
if (std::binary_search (v.begin(), v.end(), 3))
std::cout << "found!\n"; else std::cout << "not found.\n";
// using myfunction as comp:
std::sort (v.begin(), v.end(), myfunction);
std::cout << "looking for a 6... ";
if (std::binary_search (v.begin(), v.end(), 6, myfunction))
std::cout << "found!\n"; else std::cout << "not found.\n";
return 0;
}
As Piotr said, this will not give you the index, but a yes/no answer. However, is should be the simplest approach, thus the fastest.
I'm using Armadillo to do linear algebra calculation in C++.
For example, there is a
vector a = (1,1,2,2,0,2,1,0)
I wish return a matrix
(0, 2) //means 0 shows 2 times in the vector
(1, 3) //1 shows 3 times
(2, 3) //2 shows 3 times
Is there any function can fulfill such job?
As mentioned in comments you could use a std::map to collect the results. Then you can convert to a matrix as you see fit. You could skip the map step and use a matrix directly if it's already pre-initialised with the rows you're after.
As for a function to do this, you can use std::for_each from <algorithm> along with a lambda expression, although it seems overkill when a loop would be fine.
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
using namespace std;
int main()
{
vector<int> v{1,1,2,2,0,2,1,0};
map<int,int> dup;
for_each( v.begin(), v.end(), [&dup]( int val ){ dup[val]++; } );
for( auto p : dup ) {
cout << p.first << ' ' << p.second << endl;
}
return 0;
}
Here's another solution, using only Armadillo functions, and a C++11 compiler:
vec a = {1,1,2,2,0,2,1,0}; // vec holds elements of type 'double'
vec b = unique(a);
uvec c = hist(a,b); // uvec holds unsigned integers
mat X(b.n_rows, 2);
X.col(0) = b;
X.col(1) = conv_to<vec>::from(c);
X.print("X:");
Explanation:
vec b = unique(a) creates a vector containing the unique elements of a, sorted in ascending order
uvec c = hist(a,b) creates a histogram of counts of elements in a, using b as the bin centers
conv_to<vec>::from(c) converts c (vector with unsigned integers) to the same vector type as a
Suppose we have a vector/array in C++ and we wish to count which of these N elements has maximum repetitive occurrences and output the highest count. Which algorithm is best suited for this job.
example:
int a = { 2, 456, 34, 3456, 2, 435, 2, 456, 2}
the output is 4 because 2 occurs 4 times. That is the maximum number of times 2 occurs.
Sort the array and then do a quick pass to count each number. The algorithm has O(N*logN) complexity.
Alternatively, create a hash table, using the number as the key. Store in the hashtable a counter for each element you've keyed. You'll be able to count all elements in one pass; however, the complexity of the algorithm now depends on the complexity of your hasing function.
Optimized for space:
Quicksort (for example) then iterate over the items, keeping track of largest count only.
At best O(N log N).
Optimized for speed:
Iterate over all elements, keeping track of the separate counts.
This algorithm will always be O(n).
If you have the RAM and your values are not too large, use counting sort.
A possible C++ implementation that makes use of STL could be:
#include <iostream>
#include <algorithm>
#include <map>
// functor
struct maxoccur
{
int _M_val;
int _M_rep;
maxoccur()
: _M_val(0),
_M_rep(0)
{}
void operator()(const std::pair<int,int> &e)
{
std::cout << "pair: " << e.first << " " << e.second << std::endl;
if ( _M_rep < e.second ) {
_M_val = e.first;
_M_rep = e.second;
}
}
};
int
main(int argc, char *argv[])
{
int a[] = {2,456,34,3456,2,435,2,456,2};
std::map<int,int> m;
// load the map
for(unsigned int i=0; i< sizeof(a)/sizeof(a[0]); i++)
m [a[i]]++;
// find the max occurence...
maxoccur ret = std::for_each(m.begin(), m.end(), maxoccur());
std::cout << "value:" << ret._M_val << " max repetition:" << ret._M_rep << std::endl;
return 0;
}
a bit of pseudo-code:
//split string into array firts
strsplit(numbers) //PHP function name to split a string into it's components
i=0
while( i < count(array))
{
if(isset(list[array[i]]))
{
list[array[i]]['count'] = list + 1
}
else
{
list[i]['count'] = 1
list[i]['number']
}
i=i+1
}
usort(list) //usort is a php function that sorts an array by its value not its key, Im assuming that you have something in c++ that does this
print list[0]['number'] //Should contain the most used number
The hash algorithm (build count[i] = #occurrences(i) in basically linear time) is very practical, but is theoretically not strictly O(n) because there could be hash collisions during the process.
An interesting special case of this question is the majority algorithm, where you want to find an element which is present in at least n/2 of the array entries, if any such element exists.
Here is a quick explanation, and a more detailed explanation of how to do this in linear time, without any sort of hash trickiness.
If the range of elements is large compared with the number of elements, I would, as others have said, just sort and scan. This is time n*log n and no additional space (maybe log n additional).
THe problem with the counting sort is that, if the range of values is large, it can take more time to initialize the count array than to sort.
Here's my complete, tested, version, using a std::tr1::unordered_map.
I make this approximately O(n). Firstly it iterates through the n input values to insert/update the counts in the unordered_map, then it does a partial_sort_copy which is O(n). 2*O(n) ~= O(n).
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <iostream>
namespace {
// Only used in most_frequent but can't be a local class because of the member template
struct second_greater {
// Need to compare two (slightly) different types of pairs
template <typename PairA, typename PairB>
bool operator() (const PairA& a, const PairB& b) const
{ return a.second > b.second; }
};
}
template <typename Iter>
std::pair<typename std::iterator_traits<Iter>::value_type, unsigned int>
most_frequent(Iter begin, Iter end)
{
typedef typename std::iterator_traits<Iter>::value_type value_type;
typedef std::pair<value_type, unsigned int> result_type;
std::tr1::unordered_map<value_type, unsigned int> counts;
for(; begin != end; ++begin)
// This is safe because new entries in the map are defined to be initialized to 0 for
// built-in numeric types - no need to initialize them first
++ counts[*begin];
// Only need the top one at this point (could easily expand to top-n)
std::vector<result_type> top(1);
std::partial_sort_copy(counts.begin(), counts.end(),
top.begin(), top.end(), second_greater());
return top.front();
}
int main(int argc, char* argv[])
{
int a[] = { 2, 456, 34, 3456, 2, 435, 2, 456, 2 };
std::pair<int, unsigned int> m = most_frequent(a, a + (sizeof(a) / sizeof(a[0])));
std::cout << "most common = " << m.first << " (" << m.second << " instances)" << std::endl;
assert(m.first == 2);
assert(m.second == 4);
return 0;
}
It wil be in O(n)............ but the thing is the large no. of array can take another array with same size............
for(i=0;i
mar=count[o];
index=o;
for(i=0;i
then the output will be......... the element index is occured for max no. of times in this array........
here a[] is the data array where we need to search the max occurance of certain no. in an array.......
count[] having the count of each element..........
Note : we alrdy knw the range of datas will be in array..
say for eg. the datas in that array ranges from 1 to 100....... then have the count array of 100 elements to keep track, if its occured increament the indexed value by one........
Now, in the year 2022 we have
namespace aliases
more modern containers like std::unordered_map
CTAD (Class Template Argument Deduction)
range based for loops
using statment
the std::ranges library
more modern algorithms
projections
structured bindings
With that we can now write:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
namespace rng = std::ranges;
int main() {
// Demo data
std::vector data{ 2, 456, 34, 3456, 2, 435, 2, 456, 2 };
// Count values
using Counter = std::unordered_map<decltype (data)::value_type, std::size_t> ;
Counter counter{}; for (const auto& d : data) counter[d]++;
// Get max
const auto& [value, count] = *rng::max_element(counter, {}, &Counter::value_type::second);
// Show output
std::cout << '\n' << value << " found " << count << " times\n";
}