FAQ: Vectors - Review

I am not sure why I am getting an error.

Error Message:
review.cpp: In function ‘int main()’:
review.cpp:20:12: error: no match for ‘operator+=’ (operand types are ‘int’ and ‘std::vector’)
addEve += vecNums{i};
~^~~~

When i change the code to " addEve = addEve + vecNums{i} " it gives me a more complicated error.

Am i missing a library?

Im getting the error:

review.cpp: In function ‘int main()’:
review.cpp:10:9: error: ‘vector’ was not declared in this scope
     if (vector[i] % 2 == 0) {
         ^~~~~~
review.cpp:10:9: note: suggested alternative:
In file included from /usr/include/c++/7/vector:64:0,
                 from review.cpp:2:
/usr/include/c++/7/bits/stl_vector.h:216:11: note:   ‘std::vector’
     class vector : protected _Vector_base<_Tp, _Alloc>
           ^~~~~~

Even though i did do

#include <iostream>
#include <vector>

my code:

#include <iostream>
#include <vector>

int main() {
  
  int e = 0;
  int o = 1;
  std::vector<int> number = {2, 4, 3, 6, 1, 9};
  for (int i = 0; i < number.size(); i++) {
    if (vector[i] % 2 == 0) {
      e = vector[i] + e;
    }
    else {
      o = vector[i] * o;
    }
  }
  std::cout << "Sum of even numbers is " << e << " \n";
  std::cout << "Product of oss numbers is " << o << " \n";
}

Edit: nevermind, i was being stupid. I named the vector “number”, but referred to it as “vector”

1 Like

Hello! I’m a little confused on the vectors here. Mostly in the for/if statements.

for (int i = 0; i < vector.size(); i++) {

for (int i = 0; i < vector.size(); i++) {

    if (vector[i] % 2 == 0) {

      total_even = total_even + vector[i];

    } else {

      product_odd = product_odd * vector[i];

    }

  }

how is it refering back to “i” after the vector. To me, “i” is just an integer we created for the “for” loop and not something that could be referenced back like it is. If that makes sense or im just not understanding it at all. If anyone could explain it a little better that would be awesome.

Hello, @object7682468337, and welcome to the forums.

In C++, a vector is similar to an array. The i in the for loop is used to access elements in the vector by their index. If you had a vector named letters containing {'a', 'b', 'c', 'd'}, letters[0] would refer to ‘a’, letters[1] would refer to ‘b’, and so on. letters.size() would return the number of elements in the vector which in this case is 4. Keep in mind that since the indices begin at 0 that the 4 valid indices are 0, 1, 2, 3.

In your example, you have a vector named vector which evidently contains integers. The for loop iterates through each value in the vector, and performs either addition or multiplication depending on whether the value is even or odd.

1 Like

If you want to access an element at a certain index of the vector, you should use square brackets [] instead of curly braces {} i.e. vecNums[i]

I’ve looked at the solution for this problem even though i did solve it myself. I’m just wondering if my way is correct or i just made things more complicated for myself. Thanks for any input!

#include <iostream>
#include <vector>

int main (){

int even_sum = 0;
int odd_product = 1;

std::vector<int> even{2, 4, 6};
std::vector<int> odd{1, 3, 9};

for (int i = 0; i < even.size(); i++){
  even_sum = even_sum + even[i];
}
for (int k = 0; k < odd.size(); k++){
  odd_product = odd_product * odd[k];
}

std::cout << "Sum of even numbers is " << even_sum << "\n";
std::cout << "Product of odd numbers is " << odd_product << "\n";

}
1 Like

You have manually separated the vector of integers e.g. {2, 4, 3, 6, 1, 9} into an even and an odd vector. If you had some code which did the separation of the single vector into the two vectors based on some logic/calculation, then the above code would be okay. But manually declaring and initializing the even and odd vectors only works if you know the input vector beforehand. Other than that, your code will get the job done.

I believe it is because every time it search each elements of the vector, it will accumulate it to even number. Or having it set to 1 will think it odd number.

1 Like

So my code was a bit longer than the model answer, because I split the original vector into two (even and odd) and then worked from those. That’s going to make it less efficient in terms of runtime, but at any rate it was useful practice in actually working with vectors, so I’ll share it here.

Incidentally, I’m really disappointed with myself. I was ill yesterday and missed my regular coding session. This should not be an excuse, because I’m chronically ill, so I’m kind of beating myself up a bit here. Anyway, here’s the code if it helps anyone.

Hi nice people of the forums! I come here today because I’m having a hard time trying to code a section of this exercise. I’m trying to input from the user random numbres for the vector. This is my code.

#include <iostream>
#include <vector>

main() {

std::cout << "Type up to 10 numbers you want to add to classify \n" <<
"them by even and odd numbers and calculate the sum of even \n" <<
"numbers and the product of odd numbers.";

int a;
int b;
int c;
int d;
int e;
int f;
int g;
int h;
int i;
int j;

std::cin >> a >> b >> c >> d >> e >> f >> g
>> h >> i >> j;  

}

Any ideas why this doesn´t work? Thanks for your time and paitience!

I don’t think the Codecademy compiler for this particular exercise allows user inputs to be accepted.
If you try running your code in an environment other than Codecademy (such as Online C++ Compiler - online editor), your code will work.

1 Like

Thank you very much my forum gentle being! :smiley: :smiley: :smiley:

1 Like

Hey all, I was able to get the desired output however I was wondering why an alternative, slightly different code wouldn’t work.

It compiles fine and when it runs, it prints nothing to the terminal.

The original code had it so in the final if and else code blocks, I would print the input string’s current iteration instead of the output vector’s current iteration.
Not sure why it doesn’t work because what I thought I did was pushback the input string’s current iteration into the output vector, making the output vector’s corresponding index value the same, yet the result doesn’t reflect this expectation.

#include <iostream>
#include <vector>
#include <string>

int main()
  {
    // Whale, whale, whale.
    // What have we got here?

    std::string input_string = "Example";

    std::vector<char> output_vector;

    for (int i = 0;  i < input_string.size(); i++) //for looping within the input string
      {
        if ( input_string[i] == 'u' or input_string[i] == 'U' or input_string[i] == 'e' or input_string[i] == 'E' or input_string[i] == 'a' or input_string[i] == 'A' or input_string[i] == 'o' or input_string[i] == 'O' or input_string[i] == 'i' or input_string[i] == 'I' ) //filtering for vowels
          {
            if ( input_string[i] == 'a' or input_string[i] == 'A' or input_string[i] == 'o' or input_string[i] == 'O' or input_string[i] == 'i' or input_string[i] == 'I' ) //filtering for vowels to be printed once
              {
                output_vector.push_back(input_string[i]);
                std::cout << output_vector[i];
              }
            else //filtering for vowels to be printed twice
              {
                output_vector.push_back(input_string[i]);
                output_vector.push_back(input_string[i]);
                std::cout << output_vector[i];
                std::cout << output_vector[i];
              }
          }
      }

    
  }

I didn’t pull this up in the compiler but my first suggestion is to remove or and replace with ||

2 Likes

input_string = “Example”
Your program outputs: EEa

Here is what your code is doing:
i = 0 >> input_string[0] is E >> You push back two E’s into the output_vector which becomes [‘E’, ‘E’] and then std::cout << output_vector[0] prints two E’s to the terminal because you have two cout statements.
i = 1 >> input_string[1] is x >> Do nothing
i = 2 >> input_string[2] is a >> You push back ‘a’ into the output_vector which becomes [‘E’, ‘E’, ‘a’] and then std::cout output_vector[2] prints ‘a’ to the terminal.
i = 3 >> input_string[3] is m >> Do nothing
i = 4 >> input_string[4] is p >> Do nothing
i = 5 >> input_string[5] is l >> Do nothing
i = 6 >> input_string[6] is e >> You push back two e’s into the output_vector which becomes [‘E’, ‘E’, ‘a’, ‘e’, ‘e’] and then std::cout output_vector[6] goes out of range because the output vector doesn’t have any element at index 6.

… that worked.
lol, it looks like the || logical operator works while the or logical operator doesn’t, as the output vector actually is pushed back the iteration’s character.
I think codecademy’s browser doesn’t work with this alternative syntax, in fact I tested it with another code browser and it worked.

please help i am getting 3565323 for my odds code is

#include <iostream>
#include <vector>

int main() {
  
  int even = 0;
  int odd = 1;
  std::vector<int> numbers = {2, 4, 3, 6, 1, 9};

  for (int i = numbers.size(); i >= 0; i--) {

    if (numbers[i] % 2 == 0) {

      even += numbers[i];

    }

    else {

      odd  *= numbers[i];

    }

  }

  std::cout << "Sum of evens is " << even << "\n";
  std::cout << "Product of odds is " << odd;
  
}

it throws no errors however so i don’t know what to do

You have tried to iterate over the numbers vector in reverse. Nothing wrong with that, but you have to be careful with how you are initializing your loop variable: int i = numbers.size()
size() gives you how many elements are present in your vector. For this particular example, the size will be 6 because there are six elements in the numbers vector. But in C++ the index starts at 0. If you want to access the last element i.e. the sixth element, then you want to access numbers[5].
So, you should edit your initialization to int i = numbers.size() - 1
With your present code, in your very first iteration you try to access numbers[6] which is out of bounds. Some languages will give you an error when you go out of bounds, but in C++ you may not get an error. Instead, you get undefined behavior.

why everybody trying iterate this code?

mine looks like this:

#include

#include

int main(){

std::vector<int> num = {2, 4, 3, 6, 1, 9};

int eNum = 0;

int oNum = 0;

eNum = num[0] + num[1] + num[3];

oNum = num[2] + num[4] + num[5];

std::cout << "Sum of even numbers is " << eNum << "\n";

std::cout << "Sum of even numbers is " << oNum << "\n";

also why they worte that product of odd numbers should be 27?

Suppose we had a vector of integers such as {484, 32, 1, 55, 2, 454, 22, 1, 9, 4, 3, 33, 11, 8, 6, 5}. Would you prefer to go through such a vector manually and pick out the odd and even integers along with noting their index (position)? It would make your code cumbersome and if the vector of integers is changed, you will have to rewrite your code. Instead, iterating over the vector and using logic to decide whether a number is even or odd is more useful.

The instructions specify: Write a program to find the sum of even numbers and the product of odd numbers in a vector. You have calculated the sum of odd numbers instead of their product.

2 Likes