c++ - Push_back 字符串在 vector 中的位置到 2d vector

标签 c++ string vector

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

例如:

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

将相同单词的位置推回到二维 vector 中后,它将是:

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

关于c++ - Push_back 字符串在 vector 中的位置到 2d vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199430/

相关文章:

c++ - 嵌套 if 中的范围歧义

c++ - 更新 QTextDocument 的大小

arrays - 两个 bash 数组中的模式匹配

string - 从字符串列表中查找公共(public)子字符串

r - 以编程方式将字符串宽度值插入 sprintf()

c++ - 使用 getline 拆分字符串并检查 int

c++ - 经纱透视

c++ - 0xDEADBEEF 与 NULL

c++ - 继承 vector 和初始化

vector - 通过迭代而不是使用 .push() 逐一填充结构体元素的向量