How to Access Data in a Set of Vectors?

I am trying read in a bunch of words from a file, store the words in a set (thus getting rid of any duplicates), and then print the contents of the set. I originally tried to store the words as a vector and then store the vectors in a set, but I ran into issues trying to print the set. (I was able to read in, parse the file, and store all the vectors in the set without any issue.) I eventually changed it to a set of strings which worked fine. However, I'm still curious how to print data stored in a set of vectors. I'm guessing it has something to do with pointers, but honestly, I'm still a bit fuzzy on how those work.

this is the line that throws an error: std::cout << *it << std::endl;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <set>
#include <iterator>

int main()
{
	std::vector<char> newWord;
	std::set<std::vector<char>> wordSet;
	std::set<std::vector<char>>::iterator it;

	// Suppose wordSet contains the following vectors: o,n,e; t,w,o; t,h,r,e,e

	it = wordSet.begin();
	while (it != wordSet.end()) {
		std::cout << *it << std::endl;
		it++;
	}
	std::cout << std::endl;
}
Last edited on
Well, you can't print a vector with cout. You need to cout the elements of the vector separately.

1
2
3
4
5
    for (const auto& w: wordSet) {
        for (char c: w)
            std::cout << c << ' ';
        std::cout << '\n';
    }
closed account (z05DSL3A)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <iterator>

int main ()
{
    std::set<std::vector<char>> wordSet = { {'o','n','e'}, {'t','w','o'},{'t','h','r','e','e'} };

    for (const auto& word : wordSet)
    {
        std::copy (word.begin(), word.end(), std::ostream_iterator<char>(std::cout,""));
        std::cout << "\n";
    }

}
Last edited on
Topic archived. No new replies allowed.