Push_back location of string in a vector to a 2d vector?

Hi, I'm a beginner in C++ and I would like to know how to find the location of the same words in a vector<string> and push them into a 2d vector.

for example:

vector<string> temp{"hello","hey","hey","hi","hello","hi","hey"};

after pushing back the location of the same words into a 2d vector, it will be:
1
2
3
out[0] = 0, 4,                  //for "hello"
out[1] = 1, 2, 6,               //for "hey"
out[2] = 3, 5,                  //for "hi" 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...

vector<string> temp{"hello","hey","hey","hi","hello","hi","hey"};


for(int i=0; i<temp.size(); i++){

     if (temp.at(i)==temp.at(??))
         {????
          }

}


out.push_back(???); //push back the location of same words in first row (see example)




...
Last edited on
There are many ways, depending on what you are allowed to use. I give you an example using only vectors:

1. create a vector (call it keys) with the words in temp, that appear only once. You can do this by sorting temp, then using the "std::unique" algorithm. Or you can loop over all words in temp, see if it is in keys. You can use "std::find" algorithm or loop over keys and compare. If not found in keys, add it.
2. Sort keys (not necessary, but nice), and create out as a std::vector<std::vector<size_t>>, with as many elements as keys.size(), all empty vectors std::vector<size_t>
3. Loop over temp indices. See if temp[i] is in keys. Once again, you can either loop over keys or use the "std::find" algorithm, say at index j. To the corresponding out[j] you need to append the index i

Topic archived. No new replies allowed.