Summing the indices of repeating numbers

Hello everyone,

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


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iterator>

int main()
{
	constexpr int 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
using namespace 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.
Last edited on
Thank you so much @seeplus
Thank you so much @lastchance;
IMHO using std::accumulate in this case makes better solution.
1
2
3
    const int table[] = {1,4,1,1,6,1,7,1};
    int n {1};
    cout << accumulate( cbegin(table) , cend(table) , 0 , [&]( auto& a, auto& b ){ return b==n?a+(&b-&*cbegin(table)):a; } ) << endl;
Last edited on
The requirement is to sum the indexes, not the values themselves.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main()
{
   vector<int> s = { 2, 2, 3, 3, 3, 3, 1, 1, 1, 5, 1, 4, 2 };
   int n = 2, i = 0;
   cout << "Sum for target " << n << " is " << accumulate( s.begin(), s.end(), 0, [&]( int a, int b ){ return a+(i++)*(b==n); } ) << '\n';
}


Sum for target 2 is 13
Topic archived. No new replies allowed.