试图仅仅在c ++中模拟Matlab"独特"函数

Tho*_*oth 4 c++ matlab

我有以下向量,v = [ 9 2 9 5]以及它的唯一元素c = [2 5 9]按升序排列.我想提取矢量u = [3 1 3 2].所述u载体含有在载体中的独特元素的索引c,以便重构矢量v.

我的想法是迭代v,并借助于基于唯一值构造的哈希表c来获得索引值.这有意义吗?如果是的话,你能不能请一个人提出建议c++?其他建议受到高度赞赏(我对高效实现感兴趣,因为vc矩阵足够大).

最好的问候,透特

Vla*_*cow 7

C++中的索引从0开始.所以写得更准确

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

您可以使用标准算法来完成任务.例如(这里我假设矢量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;
}
Run Code Online (Sandbox Code Playgroud)

如果需要从向量v获取唯一值std::set<int>,std::vector<int>则可以使用而不是.例如

#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;
}
Run Code Online (Sandbox Code Playgroud)