我有一个包含文件中文本行的二维 vector ,如何获取重复行的索引并对它们进行计数。
for (unsigned int i = 0; i < myFileNames.size(); ++i)
{
infile.open("Whatever\\WhereEver\\" + myFileName[i]);
if (!infile.eof())
{
std::vector < std::vector< std::string>> lines;
while (getline(infile, line))
{
std::vector < std::string> tokens;
std::istringstream ls(line);
std::string token;
while (ls >> token)
tokens.push_back(token);
if (tokens.size())
lines.emplace_back(std::move(tokens));
}
for (auto& line : lines)
{
for (auto& token : line)
std::cout << token << ' ';
std::cout << '\n';
}
}
else
{
cout << "Never opened the file line 106 .." << endl;
}
最佳答案
您可以使用 std::map
将键作为线 vector ,将 int
作为值。当您通过主 vector 时,使用 operator[]
将线 vector 插入 map 并递增 int
。
std::vector < std::vector< std::string>> lines;
std::map<std::vector<std::string>, int> line_counter;
for (const auto & e : lines)
line_counter[e]++;
这将为您计算每行的重复次数。
关于c++ - 二维 vector - 查找重复元素/获取索引位置并计算重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33400158/