UserRR UserRR - 1 month ago 8
C++ Question

C++ problems in vector usage

Let's say I input values between 0-109 several times. I have a vector that counts how many times a value in a specific range(0-9, 10-19,...100-109) has occurred.

For instance, my vector initially:

0 0 0 0 0 0 0 0 0 0 0

I give 15, 16, 88, 95, 94, 5 as input.Vector becomes:

1 2 0 0 0 0 0 0 1 2 0

Here is my code:

#include <iostream>
#include <vector>
using std::vector; using std::endl;
using std::cin; using std::cout;

int main()
{
int m=0;
vector<int>vec(11,0);//00000000000

while(cin>>m)
{
vec[m/10]=vec[m/10]+1;//ex: m=15->m/10==1->vec[1]=vec[1]+1->vec[1]==1;
}//use ctrl+z(windows) to break

cout<<"012345678910"<<endl;

for(decltype(vec.size()) i:vec)
{
cout<<vec[i];
}
}


Why my code doesn't work correctly?

P.S. Code tends to use one value for many elements of vector.

Answer

This is not want you expect:

for(decltype(vec.size()) i:vec)
   {
       cout<<vec[i];
   }

A range based for gives you element values, not element indices.

You likely want:

for(const auto& e : vec)
   {
       cout<<e;
   }