Find minimum value in vector - c++

Below I have attached code for a project that is intended to find the lowest value in a user-inputed vector, return -1 if the vector is empty, and 0 if the vector only has one index. I have run into an issue with the condition in which a vector is empty as the unit test continues to fail the returns_negative_one_for_empty_vector test.
main.cc
#include <iostream>
#include <vector>
#include "minimum.h"
int main() {
int size;
std::cout << "How many elements? ";
std::cin >> size;
std::vector<double> numbers(size);
for (int i = 0; i < size; i++) {
double value;
std::cout << "Element " << i << ": ";
std::cin >> value;
numbers.at(i) = value;
}
double index;
index = IndexOfMinimumElement(numbers);
std::cout << "The minimum value in your vector is at index" << index << std::endl;
}
minimum.cc
#include "minimum.h"
#include <vector>
int IndexOfMinimumElement(std::vector<double> input) {
int i, min_index;
double min_ = input.at(0);
for (int i = 0; i < input.size(); i++) {
if (input.at(i) < min_) {
min_index = i;
return min_index;
}
else if (input.size() == 0) {
return -1;
}
else if(input.size() == 1) {
return 0;
}
}
};
minimum.h
#include <vector>
int IndexOfMinimumElement(std::vector<double> input);

find the lowest value in a user-inputed vector, return -1 if the
vector is empty, and 0 if the vector only has one index.
Instead of writing raw for loops, this can be accomplished much more easily by using the STL algorithm functions.
There are other issues, one being that the vector should be passed by const reference, not by value. Passing the vector by-value incurs an unnecessary copy.
#include <algorithm>
#include <vector>
#include <iostream>
int IndexOfMinimumElement(const std::vector<double>& input)
{
if (input.empty())
return -1;
auto ptrMinElement = std::min_element(input.begin(), input.end());
return std::distance(input.begin(), ptrMinElement);
}
int main()
{
std::cout << IndexOfMinimumElement({ 1.2, 3.4, 0.8, 7.8 }) << std::endl;
std::cout << IndexOfMinimumElement({}) << std::endl; // empty
std::cout << IndexOfMinimumElement({3}) << std::endl; // only 1 element
return 0;
}
Output:
2
-1
0
The relevant functions are std::min_element and std::distance. The std::min_element returns an iterator (similar to a pointer) to the minimum element in the range.
The code is written with a clear understanding of what each function does -- it is practically self-documenting. To get the minimum element, you call std::min_element. To get the distance from the first to the found minimum element, you call std::distance with an iterator to the starting position and an iterator to the ending position.
The bottom line is this: the STL algorithm functions rarely, if ever, fail when given the proper input parameters. Writing raw for loops will always have a much greater chance of failure, as you have witnessed. Thus the goal is to minimize having to write such for loops.

In IndexOfMinimumElement you return on the very first iteration, as all branches of your if/else lead to a return.
If your vector contained {14, 2, 10, 1} the index it would return would be 1, because 2 is less than 14.
Instead, you want to have a couple of conditional checks at the top of your function that return based on the length of the vector.
If the function call gets past those, it should iterate over the values in the vector, checking if they are less than the running minimum value, and update the minimum index accordingly.
int IndexOfMinimumElement(std::vector<double> input) {
if (input.size() == 0) return -1;
if (input.size() == 1) return 0;
int i = 0;
double min = input[0];
int min_idx = 0;
for (auto &v : input) {
if (v < min) {
min = v;
min_idx = i;
}
++i;
}
return min_idx;
}
A minimal test:
int main() {
std::vector<double> foo { 1.2, 3.4, 0.8, 7.8 };
std::cout << IndexOfMinimumElement(foo) << std::endl;
return 0;
}
Prints, as expected:
2

Related

how to array in c++

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<double> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
for (int i = 0; i < numbers.size(); i++) {
cout << freq[numbers[i]];
}
return 0;
}
When the use inputs numbers, for example 1,1,1,2 the output should be "1" because it is the most frequent number but the output here became "3,3,3,1" How to solve this problem?
You are most of the way there. Your frequencies are all stored, and you just need to search through the unordered_map now to find the item that has the largest value. Since you're already using <algorithm> you can leverage std::max_element to help:
#include <algorithm>
#include <iostream>
#include <unordered_map>
#include <vector>
int main()
{
std::vector<int> numbers = { 1, 2, 3, 2, 3, 2, 2 };
std::unordered_map<int, int> freq;
for (int n : numbers) ++freq[n];
if (!freq.empty())
{
auto it = std::max_element(freq.begin(), freq.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
std::cout << "Most frequent is " << it->first << "\n";
}
}
Output:
Most frequent is 2
Here, a custom comparison function is supplied that tests only the frequency part of the element (otherwise the default behavior will compare the full key/value pairs which will result in finding the largest number).
Note that because the map is unordered, there won't be a predictable outcome for tie-breakers (where more than one number is the most frequent). If you need to handle that in a more predictable way, you'll need to adjust the comparison function or possibly just loop over the container yourself if it requires additional work.
One option for tie-breaking is to choose the lowest number. That could be achieved by modifying the comparison to:
return std::make_pair(a.second, b.first) < std::make_pair(b.second, a.first);
The problem is that you just output all the values in map. In a naive implementation you have to iterate through map and register the maximum value and it's frequency:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
int main()
{
using std::cin, std::cout, std::endl;
using std::vector, std::unordered_map;
int input_number = 0, max_freq = 0, max_val = 0;
cout << "How many numbers you want to input: " << endl;
cin >> input_number;
// Making input double may creates questions
vector<int> numbers(input_number);
cout << "Enter numbers from 0 to 50: " << endl;
for (int i = 0; i < input_number; ++i) {
cin >> numbers[i];
}
unordered_map<int, int> freq;
for (int i = 0; i < numbers.size(); i++) {
freq[numbers[i]]++;
}
// iterating over the map and finding max value
for (auto val : freq) {
if( val.second > max_freq) {
max_val = val.first;
max_freq = val.second;
}
}
cout << max_val;
return 0;
}
Standard maps do store values as pairs of key and value (std::pair). This can be done in easier way: you can do that right while inputting the numbers.
for (int i = 0; i < numbers.size(); i++) {
int val = numbers[i];
int curfreq = ++freq[val];
if (curfreq > max_freq) {
max_val = val;
max_freq = curfreq;
}
}
cout << max_val;
Your array freq has to proper values in it. But your logic in the print out is wrong. You are printing the numbers twice. I guess you want to print all the numbers from 0 to 50.
cout << freq[i]
Then you see which entries have values or not. Then add some logic (which doesn't exist in your code) to pick the proper value. Like the biggest count..

C++ How to sum only even values stored in vector?

I am new to C++, and I have run into a total lack of understanding on how to sum only even values stored in a vector in C++.
The task itself requests a user to input some amount of random integers, stop when input is 0, and then to return the amount of even values and the sum of those even values.
This is as far as I have managed to get:
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
while (s != 0) {
std::cin >> s;
vet.push_back(s);
}
int n = count_if(vet.begin(), vet.end(),
[](int n) { return (n % 2) == 0; });
cout << n << endl;
//here is the start of my problems and lack of undertanding. Basically bad improv from previous method
int m = accumulate(vet.begin(), vet.end(), 0,
[](int m) { for (auto m : vet) {
return (m % 2) == 0; });
cout << m << endl; //would love to see the sum of even values here
return 0;
}
The function to be passed to std::accumulate takes 2 values: current accumulation value and value of current element.
What you should do is add the value if it is even and make no change when not.
int m = accumulate(vet.begin(), vet.end(), 0,
[](int cur, int m) {
if ((m % 2) == 0) {
return cur + m; // add this element
} else {
return cur; // make no change
}
});
From c++20, you can separate out the logic that checks for even numbers, and the logic for summing up those values:
auto is_even = [](int i) { return i % 2 == 0; };
auto evens = vet | std::views::filter(is_even);
auto sum = std::accumulate(std::begin(evens), std::end(evens), 0);
Here's a demo.
This is my solution(sorry if it's not right I'm writing it on my phone)
You don't need a vector form this, you just need to check right from the input if the number is divisible to 2
My solution:(a littie bit ugly)
#include <iostream>
using namespace std;
int main()
{
int s {1};
int sum{};
int countNum{};
while (s != 0)
{
cin >> s;
if (s % 2 == 0)
{
sum += s;
countNum++;
}
}
cout << countNum << ' ' << sum;
}
i don't realy know what you want to do in the second part of your code but you can sum the even numbers by this way and i want to told you another thing when you using namespace std you don't need to write std::cin you can only write cin directly
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> vet;
int s = 1;
//Take Input
while (s != 0) {
cin >> s;
vet.push_back(s);
}
//count elements
int elements_count = vet.size(); //vet.size() return the total number of elements of vector
//store the sum here
int sum=0;
//loop on the vector and sum only even numbers
for(int i=0;i<elements_count;i++){
if(vet[i] %2 ==0)
sum += vet[i];//check of the element of index i in the vector is even if it true it will add to sum
}
cout << sum;
return 0;
}
int sumEven=0;
int v[100];
int n;//number of elements you want to enter in the array
do{cout<<"Enter n";
cin>>n;}while(n<=0);
//in a normal 1 dimensional array
for(int i=0;i<n;i++)
if(v[i]%2==0)
sumEven+=v[i];
//in a vector
vector<int> v;
for(vector<int>::iterator it=v.begin();it!=v.end();it++)
if(*it%2==0)
sumEven+=v[i];
Similar to answers above, but if you want to keep the vector of even numbers as well, here are two approaches.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec = {1,2,3,4,5,6,7,8,9,10};
// Hold onto what we know is the right answer.
int known_sum = 2+4+6+8+10;
// Copy only even values into another vector
std::vector<int> even_values;
std::copy_if(vec.begin(), vec.end(),
std::back_inserter(even_values),
[](int val){ return val%2==0; });
// Compute sum from even values vector
int even_value_sum = std::accumulate(even_values.begin(), even_values.end(), 0);
// Compute sum from original vector
int even_value_second = std::accumulate(vec.begin(), vec.end(), 0,
[](int current_sum, int new_value) {
return new_value%2==0 ? current_sum + new_value:current_sum;
}
);
// These should all be the same.
std::cout << "Sum from only even vector: " << even_value_sum << std::endl;
std::cout << "Sum from binary op in std accumulate: " << even_value_second << std::endl;
std::cout << "Known Sum: " << known_sum << std::endl;
}
Range-based for loops
A range-based for loop is arguably always a valid alternative to the STL algos, particularly in cases where the operators for the algos are non-trivial.
In C++14 and C++17
E.g. wrapping a range-based even-only accumulating for loop in an immediately-executed mutable lambda:
#include <iostream>
#include <vector>
int main() {
// C++17: omit <int> and rely on CTAD.
const std::vector<int> v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto val : v) {
if (val % 2 == 0) { sum += val; }
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}
In C++20
As of C++20, you may use initialization statements in the range-based for loops, as well as the ranges library, allowing you to declare a binary comparator in the initialization statement of the range-based for loop, and subsequently apply it the range-expression of the loop, together with the std::ranges::filter_view adaptor:
#include <iostream>
#include <vector>
#include <ranges>
int main() {
const std::vector v{1, 10, 2, 7, 4, 5, 8, 13, 18, 19};
const auto sum_of_even_values = [sum = 0, &v]() mutable {
for (auto is_even = [](int i) { return i % 2 == 0; };
auto val : v | std::ranges::views::filter(is_even)) {
sum += val;
}
return sum;
}();
std::cout << sum_of_even_values; // 42
}

c++ array any two terms are equal

In an array, how do I check if any two variables are equal in something like
total_milk[7] = { b_milk, e_milk, d_milk, g_milk, a_milk, m_milk, h_milk };
without using casework
Iterate over the elements in the array, adding each element to an unordered_set.
The return value from unordered_set::insert() will tell you whether the element already was in the set.
Use two for loops and compare each element with other elements:
bool anyTwo(total_milk a[], std::size_t n) {
for (std::size_t i = 0; i < n - 1; i++) {
for (std::size_t j = i + 1; j < n; j++) {
if (a[i] == a[j]) {
return true;
}
}
}
return false;
}
This assumes your overloaded the == operator in your class. The second for loop counter j starts from i + 1 instead of 0 or i as there is no need to compare the already compared values or compare the element with itself.
The naive approach, which is fine for small data sets, is to simply use a comparison loop where each element is compared with every other element following it - there's no point comparing with those at or before an element since either the comparison has already been done or you will be comparing an item with itself.
The following complete program illustrates this approach:
#include <iostream>
int milk[] = { 3, 1, 4, 1, 5, 9 };
int main() {
for (size_t one = 0; one < sizeof(milk) / sizeof(*milk) - 1; ++one) {
for (size_t two = first + 1; two < sizeof(milk) / sizeof(*milk); ++two) {
if (milk[one] == milk[two]) {
std::cout << "Duplicate item: " << milk[one] << '\n';
return 1;
}
}
}
std::cout << "No duplicates\n";
}
For larger data sets, you can turn to the more optimised collections provided by the C++ library, such as the sets. A set is able to hold one of each value and has the useful property that it will return the fact that you tried to insert a duplicate, by returning both an iterator to the inserted/original item and a boolean value indicating whether it was new or a duplicate.
Like the earlier program, this one shows how you can use this method:
#include <iostream>
#include <unordered_set>
int milk[] = { 3, 1, 4, 1, 5, 9 };
int main() {
std::unordered_set<int> checkSet;
for (auto val: milk) {
auto iterAndBool = checkSet.insert(val);
if (! iterAndBool.second) {
std::cout << "Duplicate item: " << val << '\n';
return 1;
}
}
std::cout << "No duplicates\n";
}
A substantial improvement could be made to that using templates. This would allow it to handle arrays of any data type (assuming it has equality operators, of course) without have to code up specialisations for each. The code for that would be along the following lines:
#include <iostream>
#include <unordered_set>
template<class T> T *CheckDupes(T *collection, size_t count) {
std::unordered_set<T> checkSet;
for (size_t idx = 0; idx < count; ++idx) {
auto iterAndBool = checkSet.insert(collection[idx]);
if (! iterAndBool.second) {
return &(collection[idx]);
}
}
return nullptr;
}
int milk[] = { 3, 1, 4, 1, 5, 9 };
int main() {
int *dupe;
if ((dupe = CheckDupes<int>(milk, sizeof(milk) / sizeof(*milk))) != nullptr) {
std::cout << "Duplicate item: " << *dupe << '\n';
return 1;
}
std::cout << "No duplicates\n";
}
The templated function above will either return nullptr (if there are no duplicates) or the address of one of the duplicates. It's a simple matter to check that return value and act appropriately.
I suspect further improvement could be made to handle other collection types (not just naked arrays) but I'll leave that as an exercise for when you've mastered simpler templates :-)

swap array values in c++

I want to shift left array values if my v=4 is in a[n],remove 4 from a[n] and at the end index add 0,how i can do this?
#include <iostream>
using namespace std;
const int n=5;
int main()
{
int a[n]={1,5,4,6,8}, v=4;
int b[n];
cout << "Enter a Value" << endl;
cout<<v<<endl;
for(int i=0; i<n; i++){
cout<<a[i];
}
cout<<endl;
for(int j=0; j<n; j++){
b[j]=a[j];
if(a[j]==v)
b[j]=a[++j];
cout<<b[j];
}
return 0;
}
#include <vector> // needed for vector
#include <algorithm> // needed for find
#include <iostream> // needed for cout, cin
using namespace std;
// Vectors are just like dynamic arrays, you can resize vectors on the fly
vector<int> a { 1,5,4,6,8 }; // Prepare required vector
int v;
cout << "enter value"; // Read from user
cin >> v;
auto itr = find( a.begin(), a.end(), v); // Search entire vector for 'v'
if( itr != a.end() ) // If value entered by user is found in vector
{
a.erase(itr); // Delete the element and shift everything after element
// Toward beginning of vector. This reduces vector size by 1
a.push_back(0); // Add 0 in the end. This increases vector size by 1
}
for( int i : a ) // Iterate through all element of a (i holds element)
cout << i; // Print i
cout << '\n'; // Line end
a few helpful links:
vector , find , iterator , erase , push_back
You could use std::rotate. I suggest that you use std::vector instead of C arrays and take full advantage of the STL algorithms. Nevertheless, below I'm illustrating two versions one with C arrays and one with std::vector:
Version with C array:
#include <iostream>
#include <algorithm>
int main()
{
int const n = 5;
int a[n] = {1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a[n - 1] = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Version with vector:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> a{1,5,4,6,8};
std::cout << "Enter a Value" << std::endl;
int v;
std::cin >> v;
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
auto it = std::find(std::begin(a), std::end(a), v);
if(it != std::end(a)) {
std::rotate(it + 1, it, std::end(a));
a.back() = 0;
}
for(auto i : a) std::cout << i<< " ";
std::cout << std::endl;
return 0;
}
Here's an example using std::array
#include <array>
#include <algorithm>
// defines our array.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
// find the position of the element with the value 4.
auto where = std::find(a.begin(), a.end(), 4);
// if it wasn't found, give up
if (where == a.end())
return 0;
// move every element past "where" down one.
std::move(where + 1, a.end(), where);
// fill the very last element of the array with zero
a[ a.size() - 1] = 0;
// loop over our array, printing it to stdout
for (int i : a)
std::cout << i << " ";
std::cout << "\n";
Why would anyone use these awkward algorithms? Well, there are a few reasons. Firstly, they are container-independant. This will work with arrays and vectors and deques, no problem. Secondly, they can be easily used to work with a whole range of elements at once, not just single items, and can copy between containers and so on. They're also type-independant... you acn have an array of strings, or an vector of ints, or other more complex things, and the algorithms will still work just fine.
They're quite powerful, once you've got over their initial user-unfriendliness.
You can always use either std::array or std::vector or whatever without using the standard library algorithms, of course.
std::array<int, 5> a = {{ 1, 2, 3, 4, 5 }};
size_t where = 0;
int to_remove = 4;
// scan through until we find our value.
while (a[where] != to_remove && where < a.size())
where++;
// if we didn't find it, give up
if (where == a.size())
return 0;
// shuffle down the values
for (size_t i = where; i < a.size() - 1; i++)
a[i] = a[i + 1];
// set the last element to zero
a[ a.size() - 1] = 0;
As a final example, you can use memmove (as suggested by BLUEPIXY) to do the shuffling-down operation in one function call:
#include <cstring>
if (where < a.size() - 1)
memmove(&a[where], &a[where + 1], a.size() - where);

Counting occurrences in a vector

This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so....
If txt file says:
7 5 5 7 3 117 5
The program outputs:
3
5 3
7 2
117
so if the number occurs more than once it outputs how many times that happens. Here is the code so far.
#include "std_lib_facilities.h"
int str_to_int(string& s)
{
stringstream ss(s);
int num;
ss >> num;
return num;
}
int main()
{
cout << "Enter file name.\n";
string file;
cin >> file;
ifstream f(file.c_str(), ios::in);
string num;
vector<int> numbers;
while(f>>num)
{
int number = str_to_int(num);
numbers.push_back(number);
}
sort(numbers.begin(), numbers.end());
for(int i = 0; i < numbers.size(); ++i)
{
if(i = 0 && numbers[i]!= numbers[i+1]) cout << numbers[i] << endl;
if(i!=0 && numbers[i]!= numbers[i-1])
{
cout << numbers[i] << '\t' << counter << endl;
counter = 0;
}
else ++counter;
}
}
Edit: Program is getting stuck. Looking for an infinite loop right now.
You could use a map of numbers to counters:
typedef map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
... then iterate over the map to print results.
EDIT:
As suggested by lazypython: if you have the TR1 extensions [wikipedia.org] available, unordered_map should have better performance...
typedef std::tr1::unordered_map<int,unsigned int> CounterMap;
CounterMap counts;
for (int i = 0; i < numbers.size(); ++i)
{
CounterMap::iterator it(counts.find(numbers[i]));
if (it != counts.end()){
it->second++;
} else {
counts[numbers[i]] = 1;
}
}
How about using a map, where the key is the number you're tracking and the value is the number of occurrences?
If you must use a vector, you've already got it sorted. So just keep track of the number you previously saw. If it is the same as the current number, increment the counter. Every time the number changes: print out the current number and the count, reset the count, set the last_seen number to the new number.
Using a map is the practical solution. What you should do is to solve this problem :)
This is called frequency counter. So, you have a sorted vector and all what you have to do is to count successive equal numbers. In other words, you have to check each number with its successor.
for(size_t i = 0; i < numbers.size(); i++)
{
size_t count = 1;
size_t limit = numbers.size() - 1;
while(i < limit && numbers[i] == numbers[i+1])
{
count++;
i++;
}
std::cout << numbers[i] << "\t" << count << std::endl;
}
This program reads strings of numbers
from a txt file, converts them to
integers, stores them in a vector, and
then tries to output them in an
organized fashion like so....(emphasis added)
What is the point of this storage step? If you are reading the numbers from a file, then you already have them in order, ready to be processed (counted) one at time, as you encounter them.
However, I would need a way for it to know when it sees a new number.
I advise you to have a look at std::set or std::map. I expect either of these containers would do what you're looking for.
Std::count() fits the bill nicely.
std::vector<int>::const_iterator cur = numbers.begin();
std::vector<int>::const_iterator last = numbers.end();
while (cur != last) {
unsigned cnt = std::count(cur, last, *cur);
std::cout << *cur;
if (cnt != 1) {
std::cout << " " << c;
}
std::cout << std::endl;
int saved = *cur;
while (*cur == saved) {
++cur;
}
}
Of course there are a bunch of other algorithms out there that will do the same job. Play with things like std::equal_range() in conjunction with std::distance() will do the job just as nicely.
That was fun:
#include <map>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iterator>
struct IncrementMap
{
IncrementMap(std::map<int,int>& m): m_map(m) {}
void operator()(int val) const
{
++m_map[val];
}
std::map<int,int>& m_map;
};
struct SpecialPrint
{
SpecialPrint(std::ostream& s): m_str(s) {}
void operator()(std::map<int,int>::value_type const& value) const
{
m_str << value.first;
if (value.second != 1)
{
m_str << "\t" << value.second;
}
m_str << "\n";
}
std::ostream& m_str;
};
int main()
{
std::fstream x("Plop");
std::map<int,int> data;
std::for_each( std::istream_iterator<int>(x),
std::istream_iterator<int>(),
IncrementMap(data)
);
std::for_each( data.begin(),
data.end(),
SpecialPrint(std::cout)
);
}