c++ - 试图仅在 C++ 中模拟 Matlab "unique"函数

标签 c++ matlab

我有以下 vector ,v = [ 9 2 9 5] 及其唯一元素 c = [2 5 9] 按升序排列。我想提取 vector u = [3 1 3 2]u vector 包含 vector c中唯一元素的索引,从而重构 vector v

我的想法是遍历 v 并借助基于 c 的唯一值构建的哈希表来获取索引值。这有意义吗?如果是的话,你能请一些人在 c++ 中提出一种方法吗?高度赞赏其他建议(我对有效的实现感兴趣,因为 vc 矩阵足够大)。

最好的问候, 托特

最佳答案

C++的索引是从0开始的,这样写比较正确

u = { 2, 0, 2, 1 };

您可以使用标准算法来完成任务。例如(这里我假设 vector c 已经以某种方式构建)

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{ 
   std::vector<int> v = { 9, 2, 9, 5 };
   std::vector<int> c = { 2, 5, 9 };

   std::vector<int> u;
   u.reserve( v.size() );

   std::transform( v.begin(), v.end(), std::back_inserter( u ),
                   [&]( int x )
                   {
                      return ( std::distance( c.begin(), 
                               std::lower_bound( c.begin(), c.end(), x ) ) );
                   } );

   for ( int x : u ) std::cout << x << ' ';
   std::cout << std::endl;
}

您可以使用 std::set<int>而不是 std::vector<int>如果您需要从 vector v 中获取唯一值。例如

#include <iostream>
#include <vector>
#include <set>
#include <iterator>
#include <algorithm>

int main()
{ 
   std::vector<int> v = { 9, 2, 9, 5 };
   std::set<int> c( v.begin(), v.end() );

   std::vector<int> u;
   u.reserve( v.size() );

   std::transform( v.begin(), v.end(), std::back_inserter( u ),
                   [&]( int x )
                   {
                      return ( std::distance( c.begin(), c.find( x ) ) );
                   } );

   for ( int x : u ) std::cout << x << ' ';
   std::cout << std::endl;
}

关于c++ - 试图仅在 C++ 中模拟 Matlab "unique"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047970/

相关文章:

matlab - 氡变换线检测

matlab - 如何查看 Matlab 函数背后的 Matlab 代码

c++ - map::const_iterator 映射类型不是 const

c++ - 编译时的整数值

arrays - 查找两个数组之间的(多集)差异

matlab - MATLAB 矢量化代码如何工作 "under the hood"?

matlab - 使用傅立叶域卷积复制 MATLAB 的 `conv2()`

c++ - CUDA Thrust 如何使用 vector 将对象传输到设备

c++ - 自定义分配器仅在 VS 2015 中以 Release模式编译

c++ - 从后台线程切换到主线程