2014-05-09 2 views
0

다음을 수행하는 방법이 있습니까? boundsprintf으로 전달 하시겠습니까?printf에 인수를 전달하십시오.

double *bounds = getBounds(); 
printf("%f-%f, %f-%f, %f-%f", 
    bounds[0], bounds[1], 
    bounds[2], bounds[3], 
    bounds[4], bounds[5]); 

// what I'd like to write instead: 
xxxprintf("%f-%f, %f-%f, %f-%f", bounds); 
+0

, 일부의 printf 구현을 허용 당신에게 옵션을 제공 새로운 포맷 변환 기능 - 예를 들어, http://www.gnu.org/software/libc/manual/html_node/Customizing-Printf.html –

+0

배열/벡터를 인쇄하는 일반적인 방법을 원하십니까? 아니면 문제는 ' printf'? – 101010

+0

@ 40two. 여섯 가지 주장을 전달하는 것은 추한 것 같아요. 루프를 사용하지 않고 다른 방식으로 이것을 풀고 싶습니다. – Anna

답변

1

나는 당신이 최적화 할 이유를 당신이 당신의 프로그램에 경계를 많이 인쇄 할 필요가 있다고 가정하고 다음과 같이 쓸 무심, 그것은 등이 발생하기 쉬운 오류


입니다

printf(BOUNDS_FORMAT, BOUNDS_ARG(bounds)); 
// ... some other code, then another call, with more text around this time: 
printf("Output of pass #%d: " BOUNDS_FORMAT "\n", passNumber, BOUNDS_ARG(bounds)); 
: 그냥 그렇게처럼 쓰기 그리고

#define BOUNDS_FORMAT "%f-%f, %f-%f, %f-%f" 
#define BOUNDS_ARG(b) b[0], b[1], b[2], b[3], b[4], b[5] 

: C에서는이 같은 매크로를 사용할 수 있습니다3210


C++에서는 std::cout 또는 이와 유사한 스트림을 사용해야합니다. 그럼 당신은 당신을 위해이 작업을 수행하는 사용자 정의 개체를 작성할 수

class PrintBounds { 
    protected: 
    const double* m_bounds; 

    public: 
    PrintBounds(const double* bounds) 
     : m_bounds(bounds) 
    { 
    } 

    friend std::ostream& operator<<(std::ostream& os, const PrintBounds& self) 
    { 
     os << self.m_bounds[0] << "-" << self.m_bounds[1] << ", " 
      << self.m_bounds[2] << "-" << self.m_bounds[3] << ", " 
      << self.m_bounds[3] << "-" << self.m_bounds[5]; 
     return os; 
    } 
}; 

그런 다음 당신은 다음과 같이 사용합니다 :

std::cout << "Some other text: " << PrintBounds(bounds) << " ...\n"; 
2

당신은 내가 C에 쓴 xxxprintf()

#include <stdio.h> 

int arrayprintf_dbl(const char *fmt, const double *data) { 
    int n = 0; 
    const char *p = fmt; 
    const double *x = data; 
    while (*p) { 
    if (*p == '%') { 
     // complicate as needed ... 
     p++; 
     if (*p != 'f') return -1; // error 
     n += printf("%f", *x++); 
    } else { 
     putchar(*p); 
     n++; 
    } 
    p++; 
    } 
    return n; 
} 

int main(void) { 
    double bonus[6] = {1, 2, 3, 4, 5, 6}; 
    arrayprintf_dbl("%f-%f, %f-%f, %f-%f\n", bonus); 
    return 0; 
} 

자신, 내가이 C++ 쉽게 (필자는 C++를 모르는)로 변환 할 수 있다고 생각 작성할 수 있습니다.

1
  • 이 난의 C++ 11 버전을 게시하도록하겠습니다 한 줄 인쇄 알고리즘. for_each과 결합하여 짝수 개의 요소가있는 컨테이너를 인쇄 할 수있는 기능 (예 : PairPrintFunctor)을 코딩했습니다. 컨테이너가 홀수 개의 요소를 포함하면 마지막 요소는 무시됩니다. 고유 한 분리 문자를 설정할 수도 있습니다.

  • 참고 그러나 반복을 피할 수는 없습니다. 배경에는 for_each으로 인한 반복적 인 절차가 있습니다. 더 휴대용 표준 방법이 없지만


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

template<typename T> 
class PairPrintFunctor 
{ 
    std::size_t   _n; 
    std::ostream  &_out; 
    std::string   _delim; 
    std::string   _sep; 
    std::shared_ptr<T> state; 
public: 
    explicit PairPrintFunctor(std::ostream &out, std::string delim = " ", std::string sep = " - ") : _n(0), _out(out), _delim(delim), _sep(sep) { } 
    void operator()(T const &elem) 
    { 
     if(state == nullptr) { 
      state.reset(new T(elem)); 
     } else { 
      if (_n > 0) _out << _delim; 
      _out << *state << _sep << elem; 
      state.reset(); 
      state = nullptr; 
      ++_n; 
     } 
    } 
}; 

int main() 
{ 
    int a[] {1, 2, 3, 4, 5, 6, 7, 8}; 
    std::for_each(std::begin(a), std::end(a), PairPrintFunctor<int>(std::cout, ", ", " --- ")); 
    std::cout << std::endl; 
    std::vector<int> v{ 10, 20, 30, 40, 50, 60, 70, 80}; 
    std::for_each(std::begin(v), std::end(v), PairPrintFunctor<int>(std::cout, ", ", " --- ")); 
    std::cout << std::endl; 
    return 0; 
} 

는 HTH

관련 문제