0

I want to print out the vector element in a set container. I did the code as follows:

int main() {
  vector<int> aa = {3, 2, 1, 1};
  vector<int> bb = {5, 1, 7, 9};

  set<vector<int>> myset; // setVector

  myset.insert(aa);
  myset.insert(bb);

  for (auto elem : myset) {
    cout << elem << ", ";
  }
  return 0;
}

However, this code can not print out the vector: (3, 2, 1, 1) and (5, 1, 7, 9).

Keren Caelen
  • 1,466
  • 3
  • 17
  • 38

3 Answers3

5

you should also loop your vector elements inside myset.

for (auto const &elem : myset) {    // loop set elements
   for (auto const &v: elem) {      // loop vector elements
      std::cout << v << ", ";       // print each vector element
   }
   std::cout << std::endl;
}
Joseph D.
  • 11,804
  • 3
  • 34
  • 67
3

auto elem: myset here elem refers to the vectors.

to print out the contents of the vectors do this:

 for (auto elem : myset)
 {
      for(auto x:elem) // elem is each vector
      {
           std::cout << x << " ";
      }
       std::cout << std::endl;   
  }

Here you iterate over the vectors in the inner for loop. Also, you might want to use auto& in the loop if you are updating elements or to prevent copies since then you get a reference.

PYA
  • 8,096
  • 3
  • 21
  • 38
  • copies for the vector objects so 2 in this contrived example. – PYA May 08 '18 at 04:01
  • I accept it since it is the first solution and works. – BioChemoinformatics May 08 '18 at 04:05
  • 1
    @PYA, `O(nm)` where `n = size of set` and `m = size of vector`. you can [refer](https://stackoverflow.com/a/15176127/8012206) more to this post. – Joseph D. May 08 '18 at 04:13
  • @codekaizer hmm vector copy is much more expensive than an integer copy so I don't think that really presents a good picture of how expensive copies might be. Will be very different for large n and small m and small n and large m but i do get your point :) – PYA May 08 '18 at 04:16
  • 1
    that's why I didn't downvote. :) was just pointing that you *might* as well not work with copies if *not necessarily needed*. – Joseph D. May 08 '18 at 04:20
  • appreciate it :) – PYA May 08 '18 at 04:21
0

In order to print which you tried. You should overload << operator.

Also you may use like this.

for (auto elem : myset) {
  cout << "("; 
  for(auto item:elem)
   {
       cout << item << ",";
   }
   cout << ")"; 
   cout << endl;   
}
Yılmaz edis
  • 146
  • 3
  • 13