Push_back字符串在向量中的位置到二维向量
Push_back location of string in a vector to a 2d vector
我想知道如何在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++;
}
}
相关文章:
- 我在二维向量中是否正确分配了内存
- 在二维向量或数组中可以存储的最大元素数是多少?
- 如何将整数字符串转换为整数的二维向量?
- 使用 C++98 标准填充二维静态向量
- C++中复向量与实向量的二维卷积
- 如何使用擦除和迭代器来删除二维向量中的项目
- 如何在二维向量c++中迭代col
- 如何在C++中将.csv文件的元素存储到二维向量中?
- std::vector::clear()ing 二维向量线程的内部向量安全吗?
- 在我为我的二维向量提供第一个值后控制台关闭
- 以C++输出二维向量
- 在 c++ 中赋值给二维向量
- 在二维向量的每一列中查找最大值
- 如何声明二维模板化类类型向量?
- 类对象初始化的二维向量
- 如何定义二维矢量哪个元素是可变大小的向量
- 有没有办法像python:np.concatenate([x,y,z],axis=1)中那样沿着列连接三个二维向量C++
- 我如何在二维向量中存储一些数组
- 我可以push_back矩形形状到继承矩形形状的类的二维向量中吗?
- 二维向量的迭代器