More Efficient Way?

Could use some help, I need the elements in the vector to be Unique(non repetitive)
Im stuck

1
2
3
4
5
6
7
8
for (int k = 1; k < letters.size(); ++k) {
		for (int i = 1; i < letters.size(); ++i) {
			if (letters[k - 1] == letters[i]) {
				letters.erase(letters.begin() + i);
			}

		}
	}
If the order of the elements is not important you can copy them in a std::set.

Another option might be to sort the vector and use one of the stl algorithms.
http://www.cplusplus.com/reference/algorithm/unique/
http://www.cplusplus.com/reference/algorithm/unique_copy/
no errors, and does not work, Could use some Help or a better way, Thanks
1
2
3
4
5
6
7
8
vector<char>::iterator it;
	it = unique(letters.begin(),letters.end());
	
	letters.resize(distance(letters.begin(), it));
	unique(letters.begin(), letters.end(), boolFunction);
	for (it = letters.begin(); it != letters.end(); ++it)
		cout << ' ' << *it;
	cout << endl;
You forgot to sort it first.
thanks, i realize my first code would also work if i sorted first
Last edited on
> More Efficient Way?

More time efficient (with a good hash function): O(n) time, O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
#include <unordered_set>

int main()
{
    std::vector<int> seq { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9 } ;

    {
        std::unordered_set<int> set { std::begin(seq), std::end(seq) } ;
        seq = { std::begin(set), std::end(set) };
    }

    for( int v : seq ) std::cout << v << ' ' ;
    std::cout << '\n' ;
}

http://rextester.com/OOCY31775
Topic archived. No new replies allowed.