我想知道如何在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)
...
答案 0 :(得分: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;
}
答案 1 :(得分: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++;
}
}