undeclared identifier / c++ - c++

I am trying to solve this simple problem in C++ (complier: Visual Studio). The result should be the smallest and largest sum you can make with the elements of a given vector, but always excluding one element when getting the sum. My solution was to make all the sums, put them in a vector, sort them and then show the first and last element.
The problem I have is that the program is not executing. I get errors like arr / vector / miniMaxSum undeclared identifier... I have all the right headers included, so I don't understand why it doesn't work...
UPDATE: My program is modified and it works now. Thank you all for your input :)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//new and working function:
void miniMaxSum(vector<int> arr) {
double minSum=0, maxSum=0;
sort(arr.begin(), arr.end());
for (int j = 0; j<arr.size()-1; j++) {
minSum = minSum + arr[j];
maxSum= maxSum + arr[j+1];
}
cout << minSum << " " << maxSum;
}
//old and not working implementation
void miniMaxSum(vector<int> arr) { //Third error here:Error C2065 'vector': undeclared identifier
vector<int> sums;
int i = 0;
while (i <= arr.size()) {
for (int j = 0; j<arr.size(); j++) {
if (i == j) { sums[i] = sums[i] + arr[j + 1]; }
else { sums[i] = sums[i] + arr[j]; }
}
i++;
}
sort(sums.begin(), sums.end());
cout << sums[0] << " " << sums[sums.size() - 1];
}
int main() {
vector<int> arr { 1,2,3,4,5 };
miniMaxSum(arr);//First error here: Error C2065 'arr': undeclared identifier / Second error also here: Error C3861 'miniMaxSum': identifier not found
}

I checked your program with Visual Studio. It compiles.
Please try to select the commands "Clean Solution" from the build menu and then "Rebuild Solution"
Maybe that will help you.
Additionally:
But when you run your program, exceptions will be thrown. This, because in Visual Studios default debug modus, out-of-bounds checks will be performed. And, in case of problems, an exception will be thrown.
And you have several out of bounds errors here. The root cause is, that you need to understand, that arrays start with index 0. And if you have an array with 5 elements, so a size of 5, then the valid 5 indices are: 0,1,2,3,4.
If you write i <= arr.size() then the last value for i will be 5. And that is out of bounds. And, you access arr[j + 1]. This will also be out of bounds.
So, your program cannot run.
Please see here your programm with comments, where I see a problem:
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std; // Should never be used. Always use fully qualified names
void miniMaxSum(vector<int> arr) { // Vector should be passed by reference to the function
vector<int> sums; // Problem. Vector is Empty. It has no element
int i = 0;
while (i <= arr.size()) { // <= is false. Arrays in C++ start with index 0. So, this will go out of bounds
for (int j = 0; j < arr.size(); j++) {
if (i == j) {
sums[i] = sums[i] + arr[j + 1]; // Will go out of bounds for i and j
}
else {
sums[i] = sums[i] + arr[j]; // Will go out of bounds for i and j
}
}
i++;
}
sort(sums.begin(), sums.end());
cout << sums[0] << " " << sums[sums.size() - 1];
}
int main() {
vector<int> arr{ 1,2,3,4,5 };
miniMaxSum(arr);
// Return missing
}
For the problem solving approach. I do not fully understand your question.
The result should be the smallest and largest sum you can make with the elements of a given vector, but always excluding one element when getting the sum
This does not seem to fit to your implementation. Example. If you would sort the std::vector in the very beginning, then the sum of the smallest element, except one, would be extremely simple. JUst sum up the first n-1 elements. For the maximum value it would be the corresponding approach.
If you clarify the requirements, I will edit my anser and add a correct solution.
Based on my original understanding, the solution could be:
#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
void showMinMaxSum(std::vector<int>& data) {
// Initialize temporary variables
int sum{}, minValue{ std::numeric_limits<int>::max() }, maxValue{ std::numeric_limits<int>::min() };;
// Calculate sum of vector elements and get may and min value
for (int temp : data) {
sum += temp;
maxValue = std::max(maxValue, temp);
minValue = std::min(minValue, temp);
}
std::cout << "Min Sum: " << sum - maxValue << " \tMax Sum: " << sum - minValue << '\n';
}
int main() {
// Test data
std::vector<int> data{ 1,2,3,4,5 };
// Calculate and show results
showMinMaxSum(data);
return 0;
}

Related

Selection Sort Implementation with C++ incorrect

really new to C++, trying to instantiate some basic algorithms with it. Having trouble returning the correct result for selection sort. Here is my code
#include <iostream>
#include <array>
#include <vector>
using namespace std;
// Selection Sort :
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
return m;
}
}
void swap(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void selectionSort(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); ++i)
{
int min = findMin(arr, i);
swap(arr[i], arr[min]); // Assume a correct swap function
}
}
}
void print(vector<int> &arr)
{
if (!arr.empty())
{
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << "";
cout << endl;
}
}
}
int main()
{
vector<int> sort;
sort.push_back(2);
sort.push_back(1);
sort.push_back(7);
sort.push_back(4);
sort.push_back(5);
sort.push_back(3);
print(sort);
cout << "this was unsorted array";
cout << endl;
cout << findMin(sort, 0);
cout << "this was minimum";
cout << endl;
selectionSort(sort);
print(sort);
}
I am getting the following results:
comparison_sort.cpp:20:1: warning: non-void function does not return a value in all control paths [-Wreturn-type]
}
^
1 warning generated.
2
1
7
4
5
3
this was unsorted array
1
this was minimum
1
2
4
5
3
0
My question is: What is causing this control path error? Why is the "7" here being replaced with a "0"?
Thanks in advance! Sorry for the noob question.
I have reviewed all my current functions and nothing seems to explain why the 7 is replaced with a 0. I have tried multiple integers and it looks like the maximum number is always replaced.
The warning is very real, and it alludes to the problem that's breaking your sort as well.
You are currently returning m inside your loop body. What that means is that if the loop is entered, then the function will return m on the very first time around the loop. It only has a chance to check the first element.
And of course, if a is the last index of the array, then the loop will never execute, and you will never explicitly return a value. This is the "control path" which does not return a value.
It's quite clear that you've accidentally put return m; in the wrong place, and even though you have good code indentation, some inexplicable force is preventing you from seeing this. To fix both the warning and the sorting issue, move return m; outside the loop:
int findMin(vector<int> &arr, int a)
{
int m = a;
for (int i = a + 1; i < arr.size(); i++)
{
if (arr[i] < arr[m])
{
m = i;
}
}
return m;
}

Error : std:: out of range. where is out of range problem?

Given the following code :
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v;
v.emplace_back(1);
v.emplace_back(2);
for(int i = 2; i < n; i++){ // Is this problem point?
int data = v.at(i-1) + v.at(i-2);
v.emplace_back(data);
}
cout << v.at(n);
return 0;
}
this code has Error that is out of range.
I think that for loop has problem.
but I'm not sure where is out of range.
Is vector container index starting 0?
In each iteration of for(int i = 2; i < n; i++) you add one element to v. After the loop v contains max(2, n) elements.
The problem is caused by
cout << v.at(n);
with n >= 2. The last valid index is v.size() - 1. But to print the last value of a vector you can simply use:
cout << v.back();

My program keeps throwing compilation error,I am not able to figure out why the error has occured

Can't seem to figure out the error that the program keeps throwing.The program keeps throwing the error when I am dereferencing an iterator.Could anyone tell me where did I go wrong?
The problem for the code goes like this "Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers."
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
int sum = 0;
unordered_map<int,int> results;
for(size_t i = 0;i < arr.size();i++)
{
results[arr[i]] = accumulate(arr.begin(),arr.end(),sum) - arr[i];
}
pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator> mn;
mn = minmax_element(results.begin(),results.end());
cout<< *mn.first<<" "<<*mn.second; //line where the error is occuring
}
Solution.cpp: In function 'void miniMaxSum(std::vector)':
Solution.cpp:9:9: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream'} and 'std::pair')
cout<< *mn.first<<" "<<*mn.second;
~~~~^~~~~~~~~~~~
Edit: my answer fixes the compilation problem, but OP function does not do what they wanted it to do. John's answer solves the real algorithmic problem.
I reworked your snippet to make it immediately compilable:
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <unordered_map>
using namespace std;
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
int sum = 0;
unordered_map<int,int> results;
for(size_t i = 0;i < arr.size();i++)
{
results[arr[i]] = accumulate(arr.begin(),arr.end(),sum) - arr[i];
}
pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator> mn;
mn = minmax_element(results.begin(),results.end());
auto minIt = mn.first;
auto maxIt = mn.second;
cout<< "key min elem: " << minIt->first << " value min elem: " << minIt->second;
cout<< "key max elem: " << maxIt->first << " value max elem: " << maxIt->second;
}
The issue is the type of mn: pair<unordered_map<int,int>::iterator,unordered_map<int,int>::iterator>. mn is a pair. With mn.first you get an iterator to a key-value pair (the pair the error refer to). Once you have your pair you need to access directly the element you are interested in. I made the passage explicit in my example. You can look here (example at the bottom): https://en.cppreference.com/w/cpp/container/unordered_map for the structure of iterators on a unordered_map .
PS: you might want to avoid using namespace std I did it to keep the differences between your and my snippet to the minimum.
So here's the way to solve your problem
void miniMaxSum(vector<int> arr) { //arr = {1,2,3,4,5}
vector<int> results(arr.size());
for (size_t i = 0; i < arr.size();i++)
{
results[i] = accumulate(arr.begin(), arr.end(), 0) - arr[i];
}
auto mn = minmax_element(results.begin(), results.end());
cout << *(mn.first) << " " << *(mn.second);
}
The basic error was that you picked unordered_map<int,int> instead of vector<int> to store your intermediate results.
And notice that the correct syntax is *(mn.first) and *(mn.second) because you have a pair of iterators not an iterator pointing at a pair.
Working example

c++ How to remove any empty elements in a two dimension vector

I'm trying to remove any empty vectors inside another vector, below is my code:
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector< vector<int> > vector(9);
vector[0].push_back(2);
vector[3].push_back(5);
cout << vector.size() << endl; // print 9
for (int i = 0; i < vector.size(); ++i) {
if (vector[i].size() == 0) {
vector.erase(vector.begin() + i);
}
}
cout << vector.size() << endl; // prints 5?
}
Now, it prints 5 in the second print statement, because once I erase, the vector immediately updates its size. So now the size is different than before, and the index is not pointing to the correct element.
Is there anyway to fix this problem, so that I can find the correct size after removing all the empty elements? In this case, it should print 2?
You need to increment the index only if you didn't remove an element.
for (int i = 0; i < vector.size(); ) {
if (vector[i].size() == 0) {
vector.erase(vector.begin() + i);
} else ++i;
}

Solving the Josephus Problem using a vector

EDIT: I seem to have sorted out the errors, at the very least, and have updated the code. However, the math still doesn't seem to be working out. Any ideas?
In short, I'm trying to write a program in C++ that will prompt the user for the number of people in the initial circle, and then tell them in which position they should stand in order to survive if k (the number of people counted to before being executed) = 3.
I've got what I think is the right idea, but I get the error "Debug Assertion Failed" and "Expression: vector erase iterator outside range" if I input k as anything other than 1, 2, or 5.
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n;//size of the circle
vector <int> circle; //the circle itself
//ask for how many people are in the circle
cin >> n;
//fill the circle with 1,2,3...n
for (int idx = 0; idx < n; idx++)
{
circle.push_back (idx+1);
}
//cout << "The size of the circle is " << circle.size() << ".\nThe highest number is " << circle[n-1] << "."; //test to make sure numbers are being assigned properly to each vector element
for (int count = 0, idx = 0; circle.size() > 1; idx++,count++)
{
//if the position (idx) is greater than the size of the circle, go back to the beginning of the circle and start counting again
if (idx >= circle.size())
{
idx = 0;
}
//every time the counter reaches three, that person is executed
if (count == 3)
{
circle.erase (circle.begin()+(idx));
count = 0;
}
}
cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";
return 0;
}
You only check for if (idx > circle.size()) and then go ahead and call circle.erase (circle.begin()+(idx));. This call isn't safe when idx == circle.size().
#Pradhan already gave you the solution to your original error (idx >= circle.size() instead of idx >= circle.size().
For why the result is still not correct:
When you erase an element, you have to adjust your index to compensate for it (subtract 1). Otherwise the index corresponds to the next element in the vector, so effectively you are always executing every 4th person not every 3rd.
Here is my version of the code:
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main(){
int n;
cin >> n;
//fill the circle with 1,2,3...n
vector <int> circle(n);
std::iota(std::begin(circle), std::end(circle),1);
int idx = -1;
while (circle.size() > 1) {
//advance by threee
idx = (idx + 3) % circle.size();
//execute Person
circle.erase(circle.begin() + (idx));
//readjust to compensate for missing element
--idx;
}
cout << "The place to stand to win the hand is position #" << circle.front() << ".\n";
}
of course, you can rewrite the loop to
int idx = 0;
while (circle.size() > 1) {
//advance by three
idx = (idx + 2) % circle.size();
//execute Person
circle.erase(circle.begin() + (idx));
}