问题描述
嗨
我有一个存储在矢量中的值列表,例如
std :: vector< int> x;
x [0] = 1;
x [1] = 4;
x [2] = 2;
x [3] = 4;
x [4] = 6;
x [5] = 1;
x [6 ] = 4;
任何人都可以提出一种有效的方法来迭代向量,这样
向量只包含唯一值,例如向量中只有一个4的实例出现在
中。也就是说,新的矢量一旦被处理,将是:
{1,4,2,6}
提前致谢
David
Hi
I have a list of values stored in a vector e.g.
std::vector<int> x;
x[0] = 1;
x[1] = 4;
x[2] = 2;
x[3] = 4;
x[4] = 6;
x[5] = 1;
x[6] = 4;
Can anybody suggest an efficient way to iterate through the vector so that
the vector only contains unique values e.g. only one instance of 4 occurs in
the vector. That is, the new vector, once processed, would be:
{1,4,2,6}
Thanks in advance
David
推荐答案
查找标准: :STL引用中的sort和std :: unique。示例:
std :: sort(x.begin(),x.end());
std :: unique(x.begin() ,x.end());
您需要包含< algorithm>首先。
HTH,
Paul
Look up std::sort and std::unique in an STL reference. Example:
std::sort(x.begin(), x.end());
std::unique(x.begin(), x.end());
You''ll need to include <algorithm> first.
HTH,
Paul
的实例。也就是说,新的向量一旦被处理,将是:
{1,4,2,6}
查找std :: sort和std :: STL参考中的唯一。示例:
std :: sort(x.begin(),x.end());
std :: unique(x.begin(),x.end());
你需要包含< algorithm>首先。
HTH,
保罗
Look up std::sort and std::unique in an STL reference. Example:
std::sort(x.begin(), x.end());
std::unique(x.begin(), x.end());
You''ll need to include <algorithm> first.
HTH,
Paul
除了当然std :: unique,就像任何其他STL算法一样,实际上不会从向量中删除
。你需要做
ox.erase(std :: unique(ox.begin(),ox.end()),ox.end());
。
john
Except of course std::unique, like any other STL algorithm, will not
actually erase the items from the vector. You need to do
ox.erase(std::unique(ox.begin(), ox.end()), ox.end());
for that.
john
这篇关于问:STL向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!