List

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <list>
using namespace std;
template <typename T>
class Set {
private:
	list<int> storage;
public:
	size_t size() const { return storage.size(); }
	void insert(const T&);
};
template <typename T>
void Set<T>::insert(const T& x)
{
	for (auto i : storage)
		if (i == x)
			return;
	storage.insert(storage.begin(), x);
}
int main()
{
	Set<int> nums;
	nums.insert(3);
	nums.insert(3);
	nums.insert(5);
	for (int i = 0; i < nums.size(); i++)
		cout << nums[i];
	system("pause");
}


I want to show all elements of nums, but my code is wrong. Can anybody help please?
Last edited on
If you want be able to access element like that you need to overload the subscript operator.

 
int operator[](std::size_t index) const;
Last edited on
Imho a list provides no subscript operator, and implementing such would be very slow at execution time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <list>
using namespace std;
template <typename T>
class Set {
private:
	list<T> storage;
	typename list<T>::iterator itr;

public:
	Set() : itr{ storage.begin() } {}  // the construtor
	size_t size() const { return storage.size(); }
	void insert(const T&);

	auto begin() { return storage.begin(); }
	auto end() { return storage.end(); }

	// operator overloads
	auto & operator*() { return *itr; }
	auto const & operator*() const { return *itr; }
	auto & operator++() { return ++itr; } //prefix
	auto & operator++(int) { auto tmp = itr; ++itr; return tmp; } //postfix
};
template <typename T>
void Set<T>::insert(const T& x)
{
	for (auto i : storage)
		if (i == x)
			return;
	storage.insert(storage.begin(), x);
}
int main()
{
	Set<int> nums;
	nums.insert(3);
	nums.insert(3);
	nums.insert(5);
	for (auto & n : nums)
		cout << n;

    // the above is 'syntactic sugar' for:
	for( auto itr = nums.begin(); itr != nums.end(); ++itr)
	    cout << *itr;
}

*edited
Last edited on
If you need fast random-access you could use std::vector instead of std::list which is probably a better choice anyway.
Last edited on
Topic archived. No new replies allowed.