Push_back расположение строки в векторе к 2d вектору

0

Я хотел бы знать, как найти расположение одних и тех же слов в vector<string> и вставить их в вектор 2d.

например:

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

после отталкивания местоположения одних и тех же слов в вектор 2d это будет:

out[0] = 0, 4,                  //for "hello"

out[1] = 1, 2, 6,               //for "hey"

out[2] = 3, 5,                  //for "hi"

Пример кода:

    ...

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)

...
Теги:
string
vector

2 ответа

1

Вы можете использовать карту для поиска ранее записанных строк:

#include <iostream>
#include <vector>
#include <unordered_map>

using namespace std;

...

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

unordered_map<string, vector<int>> out;

for(int i = 0; i < temp.size(); i++) {
    auto& t = temp[i];
    auto candidate = out.find(t);
    if(candidate == out.end()) {
        out[t] = vector<int> { i };
    } else {
        candidate->second.push_back(i);
    }
}

for(auto& o : out) {
    cout << o.first << ":";

    for(auto& i : o.second) {
        cout << " " << i;
    }
    cout << endl;
}
0

Если вам нужно использовать векторы, это даст вам необходимый результат, используя find_if и C++ 11

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <string>

using pair_element = std::pair<std::string, std::vector<int> >;

using pair_vector = std::vector<pair_element>;


pair_vector countWords(std::vector<std::string> wordVec)
{

    pair_vector pairList;

    for(int i=0; i < wordVec.size(); i++)
    {
        std::string word = wordVec[i];

        auto it = std::find_if( pairList.begin(), pairList.end(),
         [word](const pair_element& element){ return element.first == word;} );

        //Item exists
        if( it != pairList.end())
        {
            //increment count
            it->second.push_back(i);
        }
        //Item does not exist
        else
        {
            //Not found, insert
            pairList.push_back( pair_element(wordVec[i], {i}) );
        }
    }

    return pairList;
}

int main()
{
    std::vector<std::string> temp{"hello","hey","hey","hi","hello","hi","hey"};

    auto wordCount = countWords(temp);
    int count = 0;

    for(auto kv : wordCount)
    {
        std::cout << "out[" << count << "] : ";
        for(int c : kv.second)
            std::cout << c << ' ';
        std::cout << std::endl;
        count++;
    }
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню