재미있는 코드들
[C++] vector 를 cout 으로 출력해보자!
tongnamuu
2021. 11. 27. 01:08
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> x = {1,2,3,4,5};
for(auto& i : x) {
cout<< i << '\n';
}
}
간단하게 벡터를 출력하는 것은 이렇게 할 수 있다.
그런데
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> x = {1,2,3,4,5};
cout<< x;
}
단순히 cout 을 하면 출력이 되면 좋겠다라는 생각을 할 수도 있다.
파이썬은 아래와 같이 굉장히 간단하다.
x = [1, 2, 3]
print(x)
c++로도 가능하다. 한 번 알아보자.
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
template<class T>
ostream& operator<<(ostream& stream, const std::vector<T>& values)
{
copy( begin(values), end(values), ostream_iterator<T>(stream, ", ") );
return stream;
}
int main() {
vector<int> x = {1,2,3,4,5};
cout<<x;
}
vector에 대해 operator<< 를 정의해서 쓰는 방법이 있다. 이렇게 되면 구분자가 ", " 이므로
1, 2, 3, 4, 5,
가 출력된다.
그렇다면 자바의 Class 같은 것이 들어온다면 어떻게 될까?
자바는 Class에 toString을 정의하면 클래스를 출력할 때 원하는데로 출력할 수 있다.
C++에서는
class A {
int x, y;
public:
A(int _x, int _y) {
x = _x, y=_y;
}
friend ostream& operator<<(ostream& os, const A& o);
};
ostream& operator<<(ostream& os, const A& o){
os<<o.x<<' '<<o.y;
return os;
}
처럼 작성해볼 수 있다.
이제 두 개를 잘 합쳐보면 아래와 같은 코드가 나온다.
#include <iterator>
#include <vector>
#include <iostream>
using namespace std;
class A{
int x, y;
public:
A(int _x, int _y) {
x = _x, y=_y;
}
friend ostream& operator<<(ostream& stream, const A& o);
};
ostream& operator<<(ostream& stream, const A& o){
stream<<o.x<<' '<<o.y;
return stream;
}
template<class T>
ostream& operator<<(ostream& stream, const std::vector<T>& values)
{
copy( begin(values), end(values), ostream_iterator<T>(stream, "\n") );
return stream;
}
int main( )
{
vector<A> vec= { *(new A(2,3)), *(new A(4,7)) };
cout<<vec;
}
이렇게 되면 구분자를 '\n' 으로 했기 때문에
2 3
4 7
이 출력되게 된다.
굉장히 이것저것 많이 쓰였지만 main은 어떤 class 인자 를 담고있는 vector하나를 선언하고 cout 해줘서 for문없이 원하는데로 출력할 수 있다.