반응형

로그를 남기다보면, vector 내부의 모든 원소를 출력해야 하는 일이 생길 수 있다.
보통 이런 일은 주로 디버깅을 할 때 발생하긴 하지만 알아두면 로그 공해도 줄일 수 있고 나름 쓸모가 많기에 그 방법을 소개한다.

- standard out으로 바로 출력하는 방법

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

int main() {
    std::vector<float> vec = {1.2f, 3.4f, 5.6f, 7.8f};

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

    return 0;
}



- stringstream에 담아 출력하는 방법 

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

int main() {
    std::vector<float> vec = {1.2f, 3.4f, 5.6f, 7.8f};
    std::stringstream ss;

    std::copy(vec.begin(), vec.end(), std::ostream_iterator<float>(ss, " "));

    std::string result = ss.str();
    std::cout << result << std::endl;

    return 0;
}

 

반응형

+ Recent posts