我有以下 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++
中提出一种方法吗?高度赞赏其他建议(我对有效的实现感兴趣,因为 v
和 c
矩阵足够大)。
最好的问候, 托特
最佳答案
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/