gpt4 book ai didi

c++ - 使用标准库对 vector 的 vector 进行排序并计算唯一出现的频率

转载 作者:太空狗 更新时间:2023-10-29 22:54:41 26 4
gpt4 key购买 nike

给定一个 std::vector<std::vector<int>> :

  • 我想输出一个排序 std::vector<std::vector<int>>
  • 仅包含唯一 std::vector<int>
  • 以及这些独特的频率(即计数)std::vector<int>

我的问题是双重的:

  • 如何仅依靠标准库有效地实现这一目标?
  • 是什么导致下面的代码执行不佳?

我尝试了以下方法:

std::vector<std::vector<int>> responseVectors 
{
{ 2, 3, 2 },
{ 3, 2, 3 },
{ 3, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 2, 1, 2 },
{ 0, 1, 2 },
{ 2, 3, 2 },
{ 3, 2, 3 },
{ 3, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 2, 1, 2 },
{ 0, 1, 2 }
};

std::vector<std::vector<int>> uniqueResponseVectors;
uniqueResponseVectors.reserve(responseVectors.size());

std::sort(responseVectors.begin(), responseVectors.end());
std::unique_copy(responseVectors.begin(), responseVectors.end(), std::back_inserter(uniqueResponseVectors));

std::vector<int> freqTotal;
freqTotal.reserve(uniqueResponseVectors.size());

for(auto&& vector : uniqueResponseVectors)
{
int count = std::count(responseVectors.begin(), responseVectors.end(), vector);
freqTotal.push_back(count);
}

输出应该是:

for(auto&& vector : uniqueResponseVectors)
{
for(auto&& value : vector)
{
std::cout << "\t" << value << "\t";
}

std::cout << "\n";
}

// Printed result for the `uniqueResponseVectors`:
//
// 0 1 2
// 1 2 3
// 2 1 2
// 2 3 2
// 3 2 3
// 3 3 3

// Similarly for the `freqTotal`:
//
// 2
// 6
// 2
// 2
// 4
// 2

其他上下文:

  • 当我针对更大的数据集(即 responseVectors,大小为 100000,每个 std::vector<int> 的大小为 12)尝试上面的代码时,速度很慢。

  • 我也试过操纵responseVectors直接调用std::uniqueerase()在上面,以避免创建拷贝。然后我使用迭代器循环来 std::count有多少次独特的 std::vector<int>发生。然而,事实证明这更慢。

最佳答案

基于此输入,我尝试详细说明 YSC 提供的解决方案就我而言,为了更好地了解发生了什么。它归结为使用 std::map 这是一个 sorted associative container :

std::map<std::vector<int>, int> SortAndCountOccurences(std::vector<std::vector<int>>& vectors)
{
std::map<std::vector<int>, int> result;

std::for_each(vectors.begin(), vectors.end(), [&result](auto const& vector) {
++result[vector];
});

return result;
}

具有以下用法:

std::vector<std::vector<int>> responseVectors 
{
{ 2, 3, 2 },
{ 3, 2, 3 },
{ 3, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 2, 1, 2 },
{ 0, 1, 2 },
{ 2, 3, 2 },
{ 3, 2, 3 },
{ 3, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 1, 2, 3 },
{ 2, 1, 2 },
{ 0, 1, 2 }
};

std::map<std::vector<int>, int> sortedVectors = SortAndCountOccurences(responseVectors);

输出:

for(auto&& vector : sortedVectors)
{
for(auto&& value : vector.first)
{
std::cout << "\t" << value << "\t";
}

std::cout << "-> x" << vector.second << " times" << "\n";
}

// 0 1 2 -> x2 times
// 1 2 3 -> x6 times
// 2 1 2 -> x2 times
// 2 3 2 -> x2 times
// 3 2 3 -> x4 times
// 3 3 3 -> x2 times

注意: solution通过 YSC可以推广到任何可迭代的

关于c++ - 使用标准库对 vector 的 vector 进行排序并计算唯一出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479308/

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