简体   繁体   中英

How to get an index array for same value in a vector?

I'm a beginner in C++ and meet a problem.

Assuming there is a vector of integers, how could we get the index array for the same value?

ie If the vector is: [a,a,b,c,a,c,b,c] where a, b, c are integers.

Then the expected index arrays should be:

v_a = [1,2,5], v_b = [3,7], v_c = [4,6,8]

Is there any simple way in C++ to implement this?

In my opinion it is better to use std::multimap in this case because the number of different integers in the original array is unknown and as I understand can be changed.

Here is a demonstrative program

#include <iostream>
#include <vector>
#include <map>

int main( void )
{
    std::vector<char> v = { 'a', 'a', 'b', 'c', 'a', 'c', 'b', 'c' };
    std::multimap<char, size_t> m;

    for ( size_t i = 0; i < v.size(); i++ ) m.insert( { v[i], i } );

    for ( auto it = m.begin(); it != m.end(); )
    {
        auto p = m.equal_range( it->first );

        while ( p.first != p.second )
        {            
            std::cout << p.first++->second << ' ';
        }
        std::cout << std::endl;

        it = p.second;
    }        
}    

The program output is

0 1 4 
2 6 
3 5 7 

Take into account that array indices start from 0 in C++.

First you need to take in account that in C++ (as in C and Java and many others languages), array's and vector's indexes start at 0. N size means N - 1 positions. For example: one vector/array with 3 elements, goes from index 0 to index 2.

In your example: v_a = [0,1,4], v_b = [2,6], v_c = [3,5,7]

int a, b, c;
vector<int> integers;
vector<int> v_a;
vector<int> v_b;
vector<int> v_c;

void indexes(){
  for(int i = 0; i < integers.size(); i++){

    if( integers[i] == a )
      v_a.push_back(i);
    else if( integers[i] == b )
      v_b.push_back(i);
    else if( integers[i] == c )
      v_c.push_back(i);
  }
}

Well this is the solution for your problem. Since you're learning C++, you may want to take this solution and try to make it more generic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM