I'm trying to remove the biggest int element in a vector and insert it into a new vector.I already have an int that represent the highest number in the vector and one that represents the position of that number.
Heres my code:
vector2.push_back(highest);
vector1[highestpos] = vector1[vector1.size()-1];
vector1[vector1.size()-1] = highest;
vector1.pop_back();
But it returns an error. Is there anything wrong with this code?
EDIT::::::HERE IS MORE OF MY CODE. The error I get is an assertion error that says vector subscript is out of range.
while(vector1.size() > 0)
{
highest = 0;
for (int i = 0; i < vector1.size(); i++)
{
if (vector1[i] > highest)
{
highest = vector1[i];
int highestpos = i;
}
}
vector2.push_back(highest);
vector1[highestpos] = vector1[vector1.size()-1];
vector1[vector1.size()-1] = highest;
vector1.pop_back();
}
Based on the edit, the problem is that the highestpos inside the loop, to which the value of i was assigned, is not the same as the highestpos outside the loop.
Try a std::cout << highestpos << '\n'; right before vector1[highestpos] = ...
(it may also be helpful to use max_element() instead of the hand-written loop to determine the highest value and vector1.erase() to delete from the vector, although erase may indeed be less efficient than swap+pop_back)
int highestpos = i;
You're just defining a variable inside the loop. It doesn't change the value of the variable outside the loop. Change to:
highestpos = i;
Related
The point of this program is to output whether a series of digits (the number of digits undefined) is sorted or not (largest to smallest or smallest to largest).
I have defined my array in my function parameter, and I am trying to use a for loop to store the user's input, as long as it is above 0, in said array.
However, I am getting the error argument of type int is incompatible with parameter of type int*.
The exact error is the argument of type int is incompatible with parameter of type int*.
It is referring to line 22 and 23, these two;
isSorted(list[2000]); and
bool is = isSorted(list[2000]);.
I know this means my for loop is assigning a single value to my variable repeatedly from reading similar questions however I can not figure out how to fix this.
#include <iostream>
using namespace std;
bool isSorted(int list[]);
int main()
{
int i;
int list[2000];
int k = 0;
for (i = 0; i < 2000; i++)
{
int j;
while (j > 0)
{
cin >> j;
list[i] = j;
}
}
isSorted(list[2000]);
bool is = isSorted(list[2000]);
if (is == true)
cout << "sorted";
else
cout << "unsorted";
return 0;
}
bool isSorted(int list[])
{
int i = 0;
for (i = 0; i < 2000; i++)
{
if (list[i] > list[i + 1] || list[i] < list[i - 1])
{
return false;
}
else
return true;
}
}
I removed unused variable k.
Made 2000 parameterized (and set to 5 for testing).
In isSorted you are not allowed to return
true in the else as if your first element test would end in else you would return true immediately not testing other elements. But those later elements can be unsorted as well.
In isSorted you are not allowed to run the loop as for(i = 0; i < 2000; i++), because you add inside the for loop 1 to i and end up querying for i == 1999 list[2000], which is element number 2001 and not inside your array. This is correct instead: for (i = 0; i < 1999; i++). You also do not need to check into both directions.
You cannot call isSorted(list[2000]) as this would call is sorted with an int and not an int array as parameter.
You write int j without initializing it and then query while j > 0 before you cin << j. This is undefined behaviour, while most likely j will be zero, there is no guarantee. But most likely you never enter the while loop and never do cin
I renamed the isSorted as you just check in your example for ascending order. If you want to check for descending order you are welcome to train your programming skills and implementing this yourself.
Here is the code with the fixes:
#include <iostream>
using namespace std;
bool isSortedInAscendingOrder(int list[]);
const int size = 5; // Set this to 2000 again if you want
int main()
{
int i;
int list[size];
for (i = 0; i < size; i++)
{
int j = 0;
while(j <= 0)
{
cin >> j;
if(j <= 0)
cout << "rejected as equal or smaller zero" << endl;
}
list[i] = j;
}
if (isSortedInAscendingOrder(list))
cout << "sorted" << endl;
else
cout << "unsorted" << endl;
return 0;
}
bool isSortedInAscendingOrder(int list[])
{
for (int i = 0; i < size -1; i++)
{
if (list[i] > list[i + 1])
{
return false;
}
}
return true;
}
This is a definition of an array of 2000 integers.
int list[2000];
This is reading the 2000th entry in that array and undefined, because the highest legal index to access is 1999. Remember that the first legal index is 0.
list[2000]
So yes, from point of view of the compiler, the following only gives a single integer on top of being undefined behaviour (i.e. "evil").
isSorted(list[2000]);
You probably should change to this, in order to fix the immediate problem - and get quite close to what you probably want. It names the whole array as parameter. It will decay to a pointer to int (among other things loosing the information of size, but you hardcoded that inside the function; better change that by the way).
isSorted(list);
Delete the ignored first occurence (the one alone on a line), keep the second (the one assigning to a bool variable).
On the other hand, the logic of a your sorting check is flawed, it will often access outside the array, for indexes 0 and 1999. I.e. at the start and end of your loop. You need to loop over slightly less than the whole array and only use one of the two conditions.
I.e. do
for (i = 1; i < 2000; i++)
{
if (list[i] < list[i - 1])
/* ... */
The logic for checking ascending or descending sorting would have to be more complex. The question is not asking to fix that logic, so I stick with fixing the issues according to the original version (which did not mention two-way-sorting).
You actually did not ask about fixing the logic for that. But here is a hint:
Either use two loops, which you can break from as soon as you find a conflict, but do not return from the fuction immediatly.
Or use one loop and keep a flag of whether ascending or descending order has been broken. Then return true if either flag is still clear (or both, in case of all identical values) or return false if both are set.
I have a struct to assign values to it. But my programm crashs it. Hopefully you can help me.
struct HashEntry{
std::string key; //the key of the entry
bool used; //the value of the entry
int value; //marks if the entry was used before
};
HashEntry *initHashList(int N){
HashEntry* hashList = new HashEntry[N];
for (int i = 0; i <= N; i++){
hashList[i].key = " ";
hashList[i].value = -1;
hashList[i].used = false;
}
for(int i = 0; i <N; i++){
cout<<hashList[i].value<<endl;
}
return hashList;
}
You iterate through one element too many on creation:
for (int i = 0; i <= N; i++){
Shoule be
for (int i = 0; i < N; i++){
It's because with arrays being 0-based, you can't access the element N of an array of the size N, only N-1, but in return also element 0.
Also, to make the code clearer and less error prone, you could use std::array instead of a pure C style array, or even an std::vector to be able to loop through them range based. You might also rething your use of new which should be avoided in most cases. If you don't really need that, I'd change the function to
std::vector<HashEntry> initHashList(int N) {
std::vector<HashEntry> hashList(N, { "", false, -1, }); //Creating vector of N elements
for (const HashEntry& entry : hashList) { //Iterating through the elements
std::cout << entry.value << std::endl;
}
return hashList;
}
I hope this makes it clearer how you can approach such a problem.
This way of creating the vector and looping through it avoids the potential access errors and is easier to read, imo. For more information, search for std::vector, its constructors, and range-based loops.
Here's what I've got:
for (int x = 0; x < 20; x++) {
double product = day_changes[0];
if (x > 0) {
product *= day_changes[x];
}
cout << product << ", ";
}
Essentially I already have an array called "day_changes" that has values. I want to multiply all the values in the array together.
I figured that I could have product[0] = day_changes[0], but then I wanted it to go so that product*day_changes[1] = product, and so on for the rest of the array.
Instead, I am just getting the exact numbers I inputted in the first place.
Here's the output:
1, 1.0211, 1.00308, 0.99995, 0.999939, 0.995816, 1.00394, 0.999062, 0.998132, 1.00014, 0.995925, 0.9892, 1.0127, 0.995615, 1.00294, 0.992832, 0.999695, 1.02132, 0.996056, 1,
Why is this happening?
You need to move the first and last statements outside the for loop. You are reinitializing product and printing it for each element of the array.
Initialize the product to suitable value outside the loop :-
double product = 1.0; <<<<< Initialize it.
for (int x = 0; x < 20; x++)
product *= day_changes[x];
cout << product; <<<<< yuppie I got correct value.
You Can Not access a variable outside the block where it is created. Just declare double product=1.0 before the loop.
I try to make a list of digit of consequence number from 1 to 100; for example, 123456789101112..... However, when I print out the result from the list_result; there is some strange number in my list_result vector. Here the following code:
int main()
{
vector<int> list_num;
vector<int> list_result;
int count =0;
for(int index = 1; index<=100; index++)
{
count = index;
if(index<10)
{
list_result.push_back(index);
}
else
{
while(count!=0)
{
list_num.push_back(count%10);
count=count/10;
}
for(int i=0; i<=list_num.size();i++)
{
list_result.push_back(list_num[list_num.size()-i]);
}
list_num.clear();
}
for(int i = 0; i<=list_result.size(); i++)
{
cout<<list_result[i];
}
}
return 0;
}
Anyone has any ideas? Thank,
Your program exhibits undefined behavior.
for(int i=0; i<=list_num.size();i++)
{
list_result.push_back(list_num[list_num.size()-i]);
}
Valid indexes into list_num are 0 through list_num.size()-1. Yet on the first iteration of this loop, when i == 0, you attempt to access list_num[list_num.size()]. There is no such element.
Igor Tandetnik described an issue in the for loop inside the else block, but I've identified another issue, this time in the output stage of the program.
Remember that indices are zero-based, which means they run from zero to the number of elements minus one. vector::size() returns the total number of elements, in this case 100. Because you're comparing this value with the index using a less-than-or-equal inequality, you end up trying to access element 100 on the final iteration of the loop, and element 100 does not exist since the range of valid indices is 0 to 99. When writing a loop that iterates through an array or vector, you should always compare indices with array/vector sizes using strict inequalities.
In the final for loop, replace the <= with a strict < comparison so that it stops at the actual last element and not afterwards:
for(int i = 0; i<list_result.size(); i++)
{
cout<<list_result[i];
}
Wikipedia has an easy-to-understand explanation of this common programming mistake, known as an off-by-one error.
I have a program that is supposed to read in values from user into a vector. My function is then supposed to keep a running sum and start from element 1 and compare element 2 to the sum(this point it is just element 1). Move to the next element, add element 2 to the sum and see if element 3 is greater than the sum of elements 1 and 2. I am supposed to print only the elements that are greater than the sum. I'm having trouble getting it to print out any values. Could someone please let me know what I might be doing wrong? Thanks
int main()
{
vector <int> theData;
int i;
cout<< "Enter in the list of integers ending with a -1" << endl;
do
{
cin >> i;
if (i==-1)
{
break;
}
theData.push_back(i);
}while(i!=-1);
int index = 1;
int runningSum = unsortedData[i];
largeValue(unsortedData, index, runningSum);
system("PAUSE");
return 0;
}
void largeValue(vector<int> myVector, int index, int runningSum)
{
int size = myVector.size();
if (index == size)
{
return;
}
if (myVector[index] > runningSum)
{
cout << myVector[index] << " ";
runningSum += myVector[index];
index = index +1;
largeValue(myVector, index, runningSum);
}
else if (myVector[index] < runningSum)
{
runningSum += myVector[index];
index = index + 1;
largeValue(myVector, index, runningSum);
}
}
There are several errors in your code:
int runningSum = unsortedData[i];
You probably meant index, not i. Both are wrong, though: the first index in the array is 0, not 1 (which is the value of index).
Also, your recursive function contains at least one error: you don’t consider that the current element equals the sum.
Another thing: you pass the vector to your function by value – not a good idea: for each call of the function, the whole vector is copied, which may take considerable time for medium-sized vectors. In “real” code, large data types should always be passed by (const) reference. Just change the function signature slightly:
void largeValue(vector<int> const& myVector, int index, int runningSum)
This way, you pass an unmodifiable reference of your vector to the function instead of copying it. Notice that this makes it impossible to modify the data of the vector inside the function.
Firstly, your function fails to meaningfully process the case when myVector[index] == runningSum.
Secondly, the initial value of runningSum is taken from unsortedData[i] which doesn't make any sense, since i is -1 at that time. You probably meant unsortedData[0].
Early in main you use theData and later you use unsortedData. I'm not sure why the compiler hasn't complained about unsortedData not being defined.