gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:33:08 25 4
gpt4 key购买 nike

我想知道如何在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com