Home > Software engineering >  how to print all element in a vector in one message in C ?
how to print all element in a vector in one message in C ?

Time:12-17

I have a vector of struct and I need print them in a nice format, currently I have:

int k = 1; 
std::cout<< "my vector names are :" std::endl ; 
for( auto v : vec1){
                std::cout<< k    << v.name << std::endl ;  
            }

and it gives me :

my vector names are :
1 name1 
2 name2 

... but I would like to have

my vector names are : 1 name1 2 name2 ...

and also can I just use one std::cout to get "my vector names are " and all names? thanks!

CodePudding user response:

If your vector contents are able to be inserted into an output stream, you can use std::copy with a std::ostream_iterator to get close to what you're describing.

#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
#include <string>

struct A {
  int x;
  std::string y;
};

std::ostream& operator<<(std::ostream& o, const A& a) {
  return o << a.x << ": " << a.y;
}

int main() {
  std::vector<A> v { {1, "hello"}, {2, "world"} };

  std::copy(v.begin(), v.end(), std::ostream_iterator<A>(std::cout, ", "));
  std::cout << std::endl;

  return 0;
}

Running this:

$ ./a.out
1: hello, 2: world,
$

CodePudding user response:

To print the names of the elements in your vector in a single line, you can use a single std::cout statement and separate each name with a space character. Here's an example of how you can do this:

std::cout << "my vector names are: ";
for (auto v : vec1) {
  std::cout << k   << " " << v.name << " ";
}
std::cout << std::endl;

  •  Tags:  
  • c
  • Related