0

I just started C++, how can I print only rows of 2d vector?

This is how I'm trying to do it but it fails.

std::vector<std::vector<int>> matrix2d{{1, 2, 3, 4},
                                       {5, 6, 7, 8},
                                       {9, 10, 11, 12}};

for (std::vector<int> i : matrix2d) {
    std::cout << i << std::endl;
}

I get an error under std::cout <<.

Error nvalid operands to binary expression ('std::ostream' (aka 'basic_ostream<char>') and 'const std::vector<double>') candidate template ignored: deduced conflicting types for parameter '_CharT' ('char' vs. 'std::vector<double, std::allocator<double> >') candidate template ignored: could not match 'basic_string' against 'vector' candidate template ignored: could not match 'const _CharT *' against 'std::vector<double>' candidate template ignored: requirement '__and_<std::__not_<std::is_lvalue_reference<std::basic_ostream<char, std::char_traits<char> > &> >, std::__is_convertible_to_basic_ostream<std::basic_ostream<char, std::char_traits<char> > &>, st...
  • Does this answer your question? https://stackoverflow.com/questions/10750057/how-to-print-out-the-contents-of-a-vector – 463035818_is_not_an_ai May 13 '20 at 08:29
  • 3
    1) In what way does it fail? 2) Do you find that you are able to do `std::cout << x << std::endl` for `x` a `std::vector` in general, independently of the code in the question? 3) Why do some of your vectors hold `int`s and some `double`s? – gspr May 13 '20 at 08:29
  • 2
    you wrote a loop, probably because you know that there is no `operator<<` that knows how to print a 2d matrix. You need another loop, because there is also no `operator<<` that knows how to print the contents of a vector – 463035818_is_not_an_ai May 13 '20 at 08:30
  • Suggestion: Make `i` into a reference instead of copying it: `const std::vector& i`. To print the contents of `i` I suggest yet another range-based for-loop. – Ted Lyngmo May 13 '20 at 08:36
  • Just fixed my to , I get the same error using const std::vector& i – Arturas Druteika May 13 '20 at 08:57
  • 2
    Question 2 remains; can you `cout << x << endl` for `x` a `std::vector` at all? If not, you'll have to find a way to print your vector, for example by looping through it and printing the elements as you encounter them. This has nothing to do with your "matrix". – gspr May 13 '20 at 09:27
  • Do you mean for(std::vector x : matrix2d){std::cout< – Arturas Druteika May 13 '20 at 14:50
  • @ArturasDruteika I mean the `std::cout< – gspr May 14 '20 at 09:02
  • Thanks, but I already found a solution. for (auto & new_output : new_outputs) { for (double l : new_output) { std::cout << l << ' ' ; } std::cout << std::endl; } – Arturas Druteika May 15 '20 at 13:08

0 Answers0