If statement - C++ - c++

I have this array that I have created full of values and basically I want to go thru an if statement to check for every value that is input into the array is of a certain condition. The condition is fine and I have all the values that I need but this if statement is taking all the values from the redsigma array rather than each one from the array. How do I put each value into the if statement rather than the whole array. Relatively new to c++. Any help is appreciated.
for (int i = 0; i < 7990272; i++)
{
float redsigma[] = { img1->pixels[i].r + img2->pixels[i].r + img3->pixels[i].r + img4->pixels[i].r}
if (redsigma[0] > lbounds && redsigma[0] < upbounds)
{
do work blah blah blah
}
}

You need to use a for-loop to iterate over the elements:
for(int i = 0; i < the length of redsigma; ++i) {
if(redsigma[i] meets conditions) {
}
}
I recommend that you use std::vector instead of an array.

Related

understanding what this line of code does

So I'm supposed to write a function that deletes a duplicate and was having a hard time understanding a certain line.
void repeat(char arr[], int times[],int &arraySize)
{
{
for(int i = 0; i<arraySize; i++)
{
for(int j =i+1; j<arraySize; j++)
{
if(arr[i]==arr[j])
{
for(int c = j; c < arraySize-1; c++){
arr[c] = arr[c+1];
}
arraySize--;
}
}
}
}
}
***for(int c = j; c < arraySize-1; c++){
arr[c] = arr[c+1];***
Are these lines looping through all the way to the last element of the array? Also a bit confused about arr[c] = arr[c+1]; why do we need that?
To delete an element in an array (whether duplicate or not -- that's irrelevant) you have to move all of the remaining elements one position down, to cover the element being deleted. And when we say 'move' we actually mean 'copy'.
So, the loop that you see replaces each element from j to arraySize - 1 with the element immediately following it. The last element does not need to be replaced, and in fact is not replaced, because the statement arraySize--; ensures that it will never be considered again.
(Also, if you think about it, if it was to be replaced, what would it be replaced with? There is no element at position [arraySize]! C++ arrays are indexed from zero, so the valid elements are from [0] to [arraySize - 1].)

Error with data store in vector in C++

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.

loop through an array in c++

I want to loop through an array that I have that has a max value of 1000. I am filling the array with values from a text file. I am trying to loop through that array but in my for loop, I do not know the length of the array, so I do not know what to put in the second part of the for loop statement. For example: I have an array called: int scores[1000]; and I am trying to iterate through this array and putting scores in a grade category. So A = 90-100, B = 80-89, C = 70-79, D = 60-69, F = 0-59.
So I dont know what my for loop would look like:
for(int i = 0; i < ...; i++){
if(scores[i] > = 90 || scores[i] <= 100){
//Do stuff...
}
I guess I am also confused as to how to get the total counts of each category at the end too. But for the most part its how to iterate through this array. I know sizeof(scores[]) wont work because that will give me the int size and not the length of the array itself. Thanks though in advance!
Actually the sizeof() should be done like this:
sizeof(scores) / sizeof(scores[0])
And this will give you the total element numbers of the array.
If you use an std::vector (link) instead, you can add elements and have the vector dynamically change size. That size can be queried easily using the size() method. If you use arrays like this, you have to keep track of the number of elements in it yourself.
If you have a vector filles with elements your loop could look like this:
std::vector<int> scores;
// fill vector
for (unsigned int i=0; i<scores.size(); i++) {
// use value
}
If you have to use arrays and actually have a scoreCount variable with the number of real values put in there, simply use that in your loop:
for (int i=0; i<scoreCount; i++) {
// use value
}
A third option, as I mentioned in the comments, would be initializing the whole array with a value that you're never using (typically -1) and then use that as a marker for filled vs empty array positions like so:
for (int i=0; i<1000; i++) {
scores[i] = -1;
}
// add real values to scores
int i=0;
while (scores[i] != -1 && i < 1000) {
// use value
i++;
}
When you populate the scores array, you need to actually count how many items you put in it. Then you remember that number and use it for iteration later. For example, you may have read your scores like this:
// Read some scores: Stop when -1 is entered, an error occurs, or 1000 values are read.
int num_scores = 0;
for( ; num_scores < 1000; num_scores++ )
{
if( !(cin >> scores[num_scores]) || scores[num_scores] == -1 ) break;
}
// Do stuff with scores...
for(int i = 0; i < num_scores; i++) {
...
}
There are some other options to consider:
use a sentinel value to represent the end of data, such as a score of -1.
use a std::vector instead.
By the way, the logical statement inside your loop will always be true. Are you sure you didn't mean to use && instead of ||?
If you really want to use a container with a fixed size, use std::array for modern C++ instead of a C-array:
#include <array>
std::array<std::int32_t, 1000> scores;
for (std::size_t i{0}; i < scores.size(); ++i) {
// Do stuff...
}
Otherwise use a std::vector:
#include <vector>
std::vector<std::int32_t> scores;
for (std::size_t i{0}; i < scores.size(); ++i) {
// Do stuff...
}
If you are able to use C++11 I also recommend to use the fixed width integer types.

C++ check if element exists in array

I've found a lot of topics like this, but it was kinda too complicated for me.
How to check if element exists in an array?
first I declare an array and put values in it
for(int l=0;l<=21;l++){
skirt[l]=l;
}
and then with another for I'd like to check if any element which exist in other array is in array skirt[];
Is there a way to write it something like this?
for(int k=0;k<=n;k++){
if(skaiciai[k]!=skirt[k]){
counter++;
}
}
The best way to do this would be to use standard algorithm, rather than a handwritten loop:
if (std::find_first_of(
skirt, skirt + skirt_size,
skaiciai, skaiciai + skaiciai_size)
!= skirt + skirt_size)
{
//skirt contained an element from skaiciai
}
The loop:
for(int k=0;k<=n;k++){
if(skaiciai[k]!=skirt[k]){
counter++;
}
}
would only compare elements at the same index in the arrays. Nested for loops are required with the outer for loop iterating over the elements in one array and the inner for loop iterating over elements in the other array:
for (int k_skirt = 0; k_skirt <= n; k_skirt++)
{
for (int k_skaiciai = 0; k_skaiciai <= n; k_skaiciai++)
{
if(skaiciai[k_skaicia] == skirt[k_skirt]){
counter++;
}
}
}
You could simply use the std::count algorithm.
auto counter = std::count( skirt, skirt+skirt_size );

C++ Checking for identical values in 2 arrays

I have 2 arrays called xVal, and yVal.
I'm using these arrays as coords. What I want to do is to make sure that the array doesn't contain 2 identical sets of coords.
Lets say my arrays looks like this:
int xVal[4] = {1,1,3,4};
int yVal[4] = {1,1,5,4};
Here I want to find the match between xVal[0] yVal[0] and xVal[1] yVal[1] as 2 identical sets of coords called 1,1.
I have tried some different things with a forLoop, but I cant make it work as intended.
You can write an explicit loop using an O(n^2) approach (see answer from x77aBs) or you can trade in some memory for performance. For example using std::set
bool unique(std::vector<int>& x, std::vector<int>& y)
{
std::set< std::pair<int, int> > seen;
for (int i=0,n=x.size(); i<n; i++)
{
if (seen.insert(std::make_pair(x[i], y[i])).second == false)
return false;
}
return true;
}
You can do it with two for loops:
int MAX=4; //number of elements in array
for (int i=0; i<MAX; i++)
{
for (int j=i+1; j<MAX; j++)
{
if (xVal[i]==xVal[j] && yVal[i]==yVal[j])
{
//DUPLICATE ELEMENT at xVal[j], yVal[j]. Here you implement what
//you want (maybe just set them to -1, or delete them and move everything
//one position back)
}
}
}
Small explanation: first variable i get value 0. Than you loop j over all possible numbers. That way you compare xVal[0] and yVal[0] with all other values. j starts at i+1 because you don't need to compare values before i (they have already been compared).
Edit - you should consider writing small class that will represent a point, or at least structure, and using std::vector instead of arrays (it's easier to delete an element in the middle). That should make your life easier :)
int identicalValueNum = 0;
int identicalIndices[4]; // 4 is the max. possible number of identical values
for (int i = 0; i < 4; i++)
{
if (xVal[i] == yVal[i])
{
identicalIndices[identicalValueNum++] = i;
}
}
for (int i = 0; i < identicalValueNum; i++)
{
printf(
"The %ith value in both arrays is the same and is: %i.\n",
identicalIndices[i], xVal[i]);
}
For
int xVal[4] = {1,1,3,4};
int yVal[4] = {1,1,5,4};
the output of printf would be:
The 0th value in both arrays is the same and is: 1.
The 1th value in both arrays is the same and is: 1.
The 3th value in both arrays is the same and is: 4.