我有以下向量,v = [ 9 2 9 5]
和它的唯一元素c = [2 5 9]
,按升序排列。我想提取向量u = [3 1 3 2]
。u
向量包含向量c
中唯一元素的索引,从而重建向量v
。
我的想法是通过v
迭代,并借助基于c
的唯一值构造的哈希表来获得索引值。这有意义吗?如果是的话,你能不能找个人推荐一种c++
的方法?另一个建议受到高度赞赏(我对高效实现感兴趣,因为v
和c
矩阵足够大)。
向你问好,托特
发布于 2014-04-13 12:38:30
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;
}
例如,如果需要从向量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;
}
https://stackoverflow.com/questions/23047970
复制相似问题