Push_back字符串在向量中的位置到二维向量

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

本文关键字:向量 二维 位置 back 字符串 Push      更新时间:2023-10-16

我想知道如何在vector<string>中找到相同单词的位置并将它们推送到二维向量中。

例如:

为了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)
...

您可以使用映射来查找以前记录的字符串:

#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;
}

如果您需要使用向量,这将使用 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++;
    }
}