Storing values from STL vector to another vector - c++

I stuck at one point and need some help.
I have a STL vector with the following values:
[1, 17, 2, 18, 3, 19, 1, 17, 2, 18, 3, 19, 1, 17, 2, 18, 3, 19].
note that first six values in a vector (i.e. 1, 17, 2, 18, 3, 19 ) can be considered as one block. So this vector has 3 blocks each with the values as described above.
Now, I want to organize this vector in a following way:
[1, 17, 1, 17, 1, 17, 2, 18, 2, 18, 2, 18, 3, 19, 3, 19, 3, 19]
.
So essentially I am picking first two values (i.e. 1, 17) from each block first and store them sequentially 3 times (basically # of blocks which in this case is 3). I then go on to pick next two values (i.e. 2, 18) and continue.
How do I achieve this..?
Any help will be greatly appreciated.
Thanks

Sound quite easy once you figure out the exact mapping. So external loop is the number of chunks in every block since that's the number of final groups, middle loop goes over each original block while inner loop just goes through every element of a chunk. Final result should be something like (untested):
std::vector organized;
organized.reserve(data.size());
const int blockSize = 6;
const int subBlockSize = 2;
assert(data.size()%blockCount == 0 && blockSize%subBlockSize == 0);
const int blockCount = data.size()/blockSize;
const int subBlockCount = blockSize/subBlockSize;
for (int i = 0; i < subBlockCount; ++i)
for (int j = 0; j < blockCount; ++j)
for (int k = 0; k < subBlockSize; ++k)
organized.push_back(subBlockSize*i + blockSize*j + k);

Just create a function shuffle(i) that takes an index into the new array, and returns an index from the original array:
#include <iostream>
#include <cstdlib>
using namespace std;
int list[] = { 1, 17, 2, 18, 3, 19, 1, 17, 2, 18, 3, 19, 1, 17, 2, 18, 3, 19 };
int shuffle( int i )
{
div_t a = div( i, 6 );
div_t b = div( a.rem, 2 );
return 2*a.quot + 6*b.quot + b.rem;
}
int main()
{
for( int i=0 ; i<18 ; ++i ) cout << list[shuffle(i)] << ' ';
cout << endl;
return 0;
}
This outputs:
1 17 1 17 1 17 2 18 2 18 2 18 3 19 3 19 3 19
Just allocate the new vector, and fill it from the old one:
new_vector[i] = list[shuffle(i)];

Related

c++ get indices of duplicating rows in 2D array

The task is following: find indices of duplicating rows of 2D array. Rows considered to be duplicated if 2nd and 4th elements of one row are equal to 2nd and 4th elements of another row.The simplest way to do it is something like that:
std::unordered_set<int> result;
for (int i = 0; i < rows_count; ++i)
{
for (int j = i + 1; j < rows_count; ++j)
{
if (arr[i][2] == arr[j][2] && arr[i][4] == arr[j][4])
{
result.push_back(j);
}
}
}
But if rows_count is very large this algorithm is too slow. So my question is there any way to get needed indices using some data structures (from stl or other) with only single loop (without nested loop)?
You could take advantage of the properties of a `std::unordered_set.
A small helper class will further ease up things.
So, we can store in a class the 2nd and 4th value and use a comparision function to detect duplicates.
The std::unordered_set has, besides the data type, 2 additional template parameters.
A functor for equality and
a functor for calculating a hash function.
So we will add 2 functions to our class an make it a functor for both parameters at the same time. In the below code you will see:
std::unordered_set<Dupl, Dupl, Dupl> dupl{};
So, we use our class additionally as 2 functors.
The rest of the functionality will be done by the std::unordered_set
Please see below one of many potential solutions:
#include <vector>
#include <unordered_set>
#include <iostream>
struct Dupl {
Dupl() {}
Dupl(const size_t row, const std::vector<int>& data) : index(row), firstValue(data[2]), secondValue(data[4]){};
size_t index{};
int firstValue{};
int secondValue{};
// Hash function
std::size_t operator()(const Dupl& d) const noexcept {
return d.firstValue + (d.secondValue << 8) + (d.index << 16);
}
// Comparison
bool operator()(const Dupl& lhs, const Dupl& rhs) const {
return (lhs.firstValue == rhs.firstValue) and (lhs.secondValue == rhs.secondValue);
}
};
std::vector<std::vector<int>> data{
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, // Index 0
{2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, // Index 1
{3, 4, 42, 6, 42, 8, 9, 10, 11, 12}, // Index 2 ***
{4, 5, 6, 7, 8, 9, 10, 11, 12, 13}, // Index 3
{5, 6, 42, 8, 42, 10, 11, 12, 13, 14}, // Index 4 ***
{6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, // Index 5
{7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, // Index 6
{8, 9, 10, 11, 12, 13, 14, 15, 16, 17}, // Index 7
{9, 10, 42, 12, 42, 14, 15, 16, 17, 18}, // Index 8 ***
{10, 11, 12, 13, 14, 15, 16, 17, 18, 19}, // Index 9
};
int main() {
std::unordered_set<Dupl, Dupl, Dupl> dupl{};
// Find the unique rows
for (size_t i{}; i < data.size(); ++i)
dupl.insert({i, data[i]});
// Show some debug output
for (const Dupl& d : dupl) {
std::cout << "\nIndex:\t " << d.index << "\t\tData: ";
for (const int i : data[d.index]) std::cout << i << ' ';
}
}

Issue with passing an argument to function

I'm working with C++ and found a problem. I want to pass an argument to a function. The argument must be a 2d array. When I try to do it, I get 2 errors:
Too many initializer values
and
initializing cannnot convert from initializer list to size_t**
How do I fix this? I've tried with changing it as 5x5 matrix, but it doesn't make it good.
size_t** matrix =
{
{1, 16, 20, 23, 25},
{6, 2, 17, 21, 24},
{10, 7, 3, 18, 22},
{13, 11, 8, 4, 19},
{15, 14, 12, 9, 5},
};
set<bool> set1 = iterateover(matrix);
The function:
std::set<bool> iterateover(size_t **arrayy)
size_t** matrix defines a pointer to a pointer to a size_t. An array is not a pointer. It can decay to a pointer, but in the case of a 2D array, it decays to a pointer to a 1D array, not to a pointer to a pointer.
The closest thing I can think of to what you seem to be after is
// here be the data
size_t actual_matrix[][5] = // note: We can omit the first dimension but we cannot
// omit the inner dimensions
{
{1, 16, 20, 23, 25},
{6, 2, 17, 21, 24},
{10, 7, 3, 18, 22},
{13, 11, 8, 4, 19},
{15, 14, 12, 9, 5},
};
// an array of pointers to the rows of actual data. This 1D array of pointers will
// decay to a size_t **
size_t * matrix[] =
{
actual_matrix[0],
actual_matrix[1],
actual_matrix[2],
actual_matrix[3],
actual_matrix[4],
};
// now we have the correct type to use with iterateover
std::set<bool> set1 = iterateover(matrix);
I want to pass an argument to a function. The argument must be a 2d array.
You can make iteratreOver a function template which can take a 2D array by reference, as shown below. You can make additional changes to the function according to your needs since it is not clear from the question what your iterateover function does. I have just printed all the elements inside the 2D array.
#include <iostream>
template<typename T,std::size_t N, std::size_t M>
void iterateOver(T (&arr)[N][M])
{
for(std::size_t i= 0; i < N; ++i)
{
for(std::size_t j = 0; j < M; ++j)
{
std::cout<<arr[i][j] <<" ";
}
std::cout<<std::endl;
}
}
int main()
{
size_t matrix[5][5] =
{
{1, 16, 20, 23, 25},
{6, 2, 17, 21, 24},
{10, 7, 3, 18, 22},
{13, 11, 8, 4, 19},
{15, 14, 12, 9, 5},
};
//call iterateOver by passing the matrix by reference
iterateOver(matrix);
}
The output of the above program can be seen here:
1 16 20 23 25
6 2 17 21 24
10 7 3 18 22
13 11 8 4 19
15 14 12 9 5

Finding the number of sum combinations between two arrays that satisfy a condition

The problem:
I have 2 arrays A[v] and M[w], with length v and w, respectively. Given two numbers p and q, I want to find how many combinations of the sum of two elements of these arrays satisfy the following condition:
p >= A[v] + M[w] <= q
An example:
Let:
A = [9, 14, 5, 8, 12, 2, 16],
v = 7,
M = [6, 2, 9, 3, 10],
w = 5,
p = 21,
q = 24
The answer will be 5, because of the following combinations:
14 + 9 = 23
14 + 10 = 24
12 + 9 = 21
12 + 10 = 22
16 + 6 = 22
What I have tried:
The following is an implementation of the problem in C++:
int K = 0; // K is the answer
for (int i=0; i<v; i++) {
for (int j=0; j<w; j++) {
if (A[v]+M[w] >= p && A[v]+M[w] <= q) {
++K;
}
}
}
As we can see the above code uses a loop inside a loop, thus making the time complexity of the program Ο(v×w), pretty slow for large arrays.
The question
Is there a fastest way to solve this problem?
Problem Summary: Given two arrays A and B with sizes v and w respectively, find the number of possible pairings of an element from A and an element from B such that the two elements have a sum that is >= p and <= q.
The simple, brute force algorithm is essentially what you have currently. The brute force algorithm would simply involve testing all possible pairs, which, as you said, would have a time complexity of O(v*w) because there are v ways to choose the first element and w ways to choose the second element when testing all the pairs.
As #thestruggler pointed out in their comment, sorting and binary search could be applied to create a significantly more efficient algorithm.
Let's say we sort B in ascending order. For the test case you provide, we would then have:
A = [9, 14, 5, 8, 12, 2, 16]
B = [2, 3, 6, 9, 10]
p = 21 and q = 24
Now, notice that for every element in a, we can calculate the range of elements in B that, when added to the element, would have a sum between p and q. We can actually find this range in O(logW) time by using what is called Binary Search. Specifically, if we were looking to pair the first number in A with numbers in B, we would binary search for the index of the first element that is >= 12 and then binary search for the index of the last element that is <= 15. The number of elements in B that would work in a pairing with the element from A is then just equal to 1 plus the difference between the two indexes.
Overall, this algorithm would have a complexity of O(WlogW + VlogW) (or O(VlogV + WlogV); if you want to go above and beyond your program could decide to sort the larger array to save time on testing). This is because sorting an array with N elements takes O(NlogN) time, and because each binary search over a sorted array with N elements takes O(logN).
This can also be solved in following way,
First sort both arrays,
[9, 14, 5, 8, 12, 2, 16] => [2, 5, 8, 9, 12, 14, 16]
[6, 2, 9, 3, 10] => [2, 3, 6, 9, 10]
Now iterate all elements of smaller array and do following,
[2, 3, 6, 9, 10],
current element is 2, subtract it with p, lets say it is num it means,
num = p - 2 = 21 - 2 = 19
Then all numbers in other array, grater than of equals to 19 will make sum 21 with 2. But no element in other array is grater than or equals to 19 It means by adding 2 with any element of other array can not grater than or equals to p,
Next element which is 3 and it also can not fulfill the requirement, same can be done with other element, so let's directly move to element 9 for explanation,
[2, 3, 6, 9, 10]
num = p - 9 = 21 - 9 = 12 and by getting lower bound of 12, we will get all numbers, those sum with 9 will be grater than or equal to p(21), as highlighted below,
[2, 5, 8, 9, 12, 14, 16],
Sum of these numbers with 9 is grater than or equals to p, now it is time to find how may of them will produce sum which is less then or equals to q, so to doing that we have to do following,
num = q - 9 = 24 - 9 = 15 and by finding upper bound of 15 will give all the numbers sum with 9 shall be less than of equals to q as highlighted below,
[2, 5, 8, 9, 12, 14, 16],
This way you can find all combinations having sum, p >= sum <= q,
#include <iostream>
#include <vector>
#include <algorithm>
std::size_t combinationCount(int p, int q, std::vector<int> arr1, std::vector<int> arr2){
std::sort(arr1.begin(), arr1.end());
std::sort(arr2.begin(), arr2.end());
std::vector<int>::const_iterator it1 = arr1.cbegin();
std::vector<int>::const_iterator endIt1 = arr1.cend();
std::vector<int>::const_iterator it2 = arr2.cbegin();
std::vector<int>::const_iterator endIt2 = arr2.cend();
if(arr2.size() < arr1.size()){
std::swap(it1, it2);
std::swap(endIt1, endIt2);
}
std::size_t count = 0;
for(; endIt1 != it1; ++it1){
int num = p - *it1;
std::vector<int>::const_iterator lowBoundOfPIt = std::lower_bound(it2, endIt2, num);
if(endIt2 != lowBoundOfPIt){
num = q - *it1;
std::vector<int>::const_iterator upBoundOfQIt = std::upper_bound(it2, endIt2, num);
count += (upBoundOfQIt - lowBoundOfPIt);
}
}
return count;
}
int main(){
std::cout<< "count = "<< combinationCount(21, 24, {9, 14, 5, 8, 12, 2, 16}, {6, 2, 9, 3, 10})<< '\n';
}
Output : 5

Max subarray with start and end index

I'm trying to find the maximum contiguous subarray with start and end index. The method I've adopted is divide-and-conquer, with O(nlogn) time complexity.
I have tested with several test cases, and the start and end index always work correctly. However, I found that if the array contains an odd-numbered of elements, the maximum sum is sometimes correct, sometimes incorrect(seemingly random). But for even cases, it is always correct. Here is my code:
int maxSubSeq(int A[], int n, int &s, int &e)
{
// s and e stands for start and end index respectively,
// and both are passed by reference
if(n == 1){
return A[0];
}
int sum = 0;
int midIndex = n / 2;
int maxLeftIndex = midIndex - 1;
int maxRightIndex = midIndex;
int leftMaxSubSeq = A[maxLeftIndex];
int rightMaxSubSeq = A[maxRightIndex];
int left = maxSubSeq(A, midIndex, s, e);
int right = maxSubSeq(A + midIndex, n - midIndex, s, e);
for(int i = midIndex - 1; i >= 0; i--){
sum += A[i];
if(sum > leftMaxSubSeq){
leftMaxSubSeq = sum;
s = i;
}
}
sum = 0;
for(int i = midIndex; i < n; i++){
sum += A[i];
if(sum > rightMaxSubSeq){
rightMaxSubSeq = sum;
e = i;
}
}
return max(max(leftMaxSubSeq + rightMaxSubSeq, left),right);
}
Below is two of the test cases I was working with, one has odd-numbered elements, one has even-numbered elements.
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
Edit: The following are the 2 kinds of outputs:
// TEST 1
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 32769 // Index is correct, but sum should be 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39 // correct
// TEST 2
Test file : T2-Data-1.txt
Array with 11 elements:
1, 3, -7, 9, 6, 3, -2, 4, -1, -9,
2,
maxSubSeq : A[3..7] = 20
Test file : T2-Data-2.txt
Array with 20 elements:
1, 3, 2, -2, 4, 5, -9, -4, -8, 6,
5, 9, 7, -1, 5, -2, 6, 4, -3, -1,
maxSubSeq : A[9..17] = 39
Can anyone point out why this is occurring? Thanks in advance!
Assuming that n is the correct size of your array (we see it being passed in as a parameter and later used to initialize midIndexbut we do not see its actual invocation and so must assume you're doing it correctly), the issue lies here:
int midIndex = n / 2;
In the case that your array has an odd number of elements, which we can represented as
n = 2k + 1
we can find that your middle index will always equate to
(2k + 1) / 2 = k + (1/2)
which means that for every integer, k, you'll always have half of an integer number added to k.
C++ doesn't round integers that receive floating-point numbers; it truncates. So while you'd expect k + 0.5 to round to k+1, you actually get k after truncation.
This means that, for example, when your array size is 11, midIndex is defined to be 5. Therefore, you need to adjust your code accordingly.

Extracting and sorting data in an array?

Here is my array:
int grid[gridsize+1] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6, 4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8, 4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8 };
Each number represents a colour, I would like to create multiple arrays for each unique number. The created arrays will store the locations of that number from the original array.
e.g
colour1[5]
[0]=0 //because the number 1 is stored in element 0.
[1]=1
[2]=8
[3]=9
The numbers in grid will change every time I run, so things need to be dynamic?
I can write inefficient code that accomplishes this, but it's just repetitive and I can't comprehend a way to turn this into something I can put in a function.
Here is what I have;
int target_number = 1
grid_size = 64;
int counter = -1;
int counter_2 = -1;
int colour_1;
while (counter < grid_size + 1){
counter = counter + 1;
if (grid[counter] == target)
counter_2 = counter_2 + 1;
colour_1[counter_2] = counter;
}
}
I have to do this for each colour, when I try to make a function, it cannot access the main array in main so is useless.
You can just use vector<vector<int>> to represent your counters. No maps or sorting are needed.
EDIT: added additional pass to determine maximum color, so no run-time resize is needed.
Here is the code:
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int grid[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, /*...*/};
const size_t gridSize = std::end(grid) - std::begin(grid);
int maxColor = *std::max_element(std::begin(grid), std::end(grid));
std::vector<std::vector<int>> colorPos(maxColor);
for (size_t i = 0; i < gridSize; ++i)
colorPos[grid[i] - 1].push_back(i);
for (size_t i = 0; i < colorPos.size(); ++i) {
std::cout << (i + 1) << ": ";
for (int p : colorPos[i])
std::cout << p << ' ';
std::cout << std::endl;
}
return 0;
}
The output:
1: 0 1 8 9 10 17
2: 2 3 4 5 6 7 14 15 22 30
3: 11 12 13 19 20 28
4: 16 24 32 33 40 48 56
5: 18 25 26 27 34 35 36 44
6: 21 23 29 31 37 38 39
7: 41 42 49 50 57 58 59 60
8: 43 45 46 47 51 52 53 54 55 61 62 63
I think you'd be best off using a counting sort, which is a sorting algorithm that works very well for sorting large groups of simple types with many duplicate values in better than O(n log n) time. Here's some sample code, annotated for clarity:
// set up our grid
int grid_raw[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2, 4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6, 4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8, 4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8};
// build a vector using our raw list of numbers. This calls the range constructor:
// (number 3) http://www.cplusplus.com/reference/vector/vector/vector/
// The trick to using sizeof is that I don't have to change anything if my grid's
// size changes (sizeof grid_raw gives the number of bytes in the whole array, and
// sizeof *grid_raw gives the number of bytes in one element, so dividing yields
// the number of elements.
std::vector<int> grid(grid_raw, grid_raw + sizeof grid_raw / sizeof *grid_raw);
// count the number of each color. std::map is an associative, key --> value
// container that's good for doing this even if you don't know how many colors
// you have, or what the possible values are. Think of the values in grid as being
// colors, not numbers, i.e. ++buckets[RED], ++buckets[GREEN], etc...
// if no bucket exists for a particular color yet, then it starts at zero (i.e,
// the first access of buckets[MAUVE] will be 0, but it remembers each increment)
std::map<int, int> buckets;
for (vector<int>::iterator i = grid.begin(); i != grid.end(); ++i)
++buckets[*i];
// build a new sorted vector from buckets, which now contains a count of the number
// of occurrences of each color. The list will be built in the order of elements
// in buckets, which will default to the numerical order of the colors (but can
// be customized if desired).
vector<int> sorted;
for (map<int, int>::iterator b = buckets.begin(); b != buckets.end(); ++b)
sorted.insert(sorted.end(), b->second, b->first);
// at this point, sorted = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, ...}
Read more about the Counting Sort (includes example python code)
Here's an ideone that demonstrates sorting your grid.
I'm not 100% sure this answers your question... but you included sorting in the title, even though you didn't say anything about it in the body of your question.
Maybe it would be better to use some associative container as for example std::unordered_map or std::multimap.
Here is a demonstrative program
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for ( int x : grid )
{
m.insert( { x, i++ } );
}
std::multimap<int, int>::size_type n = m.count( 1 );
std::cout << "There are " << n << " elements of color 1:";
auto p = m.equal_range( 1 );
for ( ; p.first != p.second ; ++p.first )
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
return 0;
}
The output
There are 6 elements of color 1: 0 1 8 9 10 17
Or
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for ( int x : grid )
{
m.insert( { x, i++ } );
}
for ( auto first = m.begin(); first != m.end(); )
{
auto n = m.count( first->first );
std::cout << "There are " << n
<< " elements of color " << first->first << ":";
auto p = m.equal_range( first->first );
for ( ; p.first != p.second ; ++p.first )
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
first = p.first;
}
return 0;
}
the output is
There are 6 elements of color 1: 0 1 8 9 10 17
There are 10 elements of color 2: 2 3 4 5 6 7 14 15 22 30
There are 6 elements of color 3: 11 12 13 19 20 28
There are 7 elements of color 4: 16 24 32 33 40 48 56
There are 8 elements of color 5: 18 25 26 27 34 35 36 44
There are 7 elements of color 6: 21 23 29 31 37 38 39
There are 8 elements of color 7: 41 42 49 50 57 58 59 60
There are 12 elements of color 8: 43 45 46 47 51 52 53 54 55 61 62 63
If you are not forced to use plain arrays, I can propose a map of colors to a vector of positions:
the map is an associative container, that for any color key returns a reference
the referenced used here will be a vector (a kind of dynamic array) containing all the positions.
Your input grid contains color codes:
typedef int colorcode; // For readability, to make diff between counts, offsets, and colorcodes
colorcode grid[] = { 1, 1, /* .....input data as above.... */ ,8 };
const size_t gridsize = sizeof(grid) / sizeof(int);
You would then define the color map:
map<colorcode, vector<int>> colormap;
// ^^^ key ^^^ value maintained for the key
With this approach, your color1[..] would then be replaced by a more dynamic corlormap[1][..]. And it's very easy to fill:
for (int i = 0; i < gridsize; i++)
colormap[grid[i]].push_back(i); // add the new position to the vector returned for the colormap of the color
To verify the result, you may iterate through the map, and for each existing value iterate through the positions:
for (auto x : colormap) { // for each color in the map
cout << "Color" << x.first << " : "; // display the color (key)
for (auto y : x.second) // and iterate through the vector of position
cout << y << " ";
cout << endl;
}
You don't know for sure how many different color codes you have, but you want to store for accodes