I am a beginner of C++ and doing some execercises. I am blocked in a point.
I have a list like this
s=[2 2 3 3 3 3 1 1 1 5 1 4 2]
I need to sum of the indices of the same numbers in this list. let me explain with an example; I assign the variable X for all repeating numbers so what I want for example for 2
X0+X1+X12
for example for 1
X6+X7+X8+X10
Since I am newly learner , I really stucked at this point, I will be very happy , if you can help me
#include <iostream>
#include <iterator>
int main()
{
constexprint list[] {2, 2, 3, 3, 3, 3, 1, 1, 1, 5, 1, 4, 2};
int num;
std::cout << "Please enter number to sum: ";
std::cin >> num;
int sum {0};
for (int l = 0; l < std::size(list); ++l)
if (list[l] == num)
sum += l;
std::cout << "Sum of indexes is: " << sum << std::endl;
}
This will sum the indexes (starting at 0) for those elements that equal the entered number.
#include <iostream>
#include <vector>
usingnamespace std;
int matchNums( const vector<int> &V, int target )
{
int total = 0;
for ( int i = 0; i < V.size(); i++ ) if ( V[i] == target ) total += i;
return total;
}
int main()
{
vector<int> s = { 2, 2, 3, 3, 3, 3, 1, 1, 1, 5, 1, 4, 2 };
int n = 2;
cout << "Sum for target " << n << " is " << matchNums( s, n );
}
Sum for target 2 is 13
You are using an awful lot of Python-like terminology. "Lists" don't have indices in C++.
You also won't be able to distinguish between "not found" and an element only appearing in the first position (index 0) of your container.