2015-02-02 3 views
0

정수를 사용자에게 물어보고 싶다고 가정하고 평균값, 모드 등을 계산하는 등의 산술 연산을 수행하고 싶습니다. 통계 함수를 적용 할 수 있도록 데이터를 수집하는 가장 효율적이고 효율적인 방법은 무엇입니까?정수 집합을 저장하는 가장 좋은 방법

답변

1

정렬 된 데이터에서 중앙 및 모드를 훨씬 쉽게 찾을 수 있습니다.

사용자가 데이터를 입력하는 경우 정렬 작업을 모든 항목에 걸쳐 적용 할 수 있으므로 배열에 삽입 정렬을 선택하는 것이 좋습니다.

데이터가 파일과 같은 전자 소스에서 나온 것이라면 아마 모든 것을 읽고 나서 정렬하는 것이 가장 좋습니다.

아무리 처리를 선택하든 좋은 캐시 동작과 효율적인 임의 액세스로 메모리를 효율적으로 사용하므로 std::vector 또는 std::deque에 저장하십시오.

1

사용 "데이터 수집"할 수있는 std::istream - 당신은 표준 입력 (키보드 기본적으로, 또는 재/파이프 파일 또는 명령 출력)을하려는 경우 특히, 중 std::cin, 그렇지 않으면 std::ifstream 파일을 직접 읽을 수 있습니다. 예를 들어 :

double my_double; 
if (!(std::cin >> my_double)) 
{ 
    std::cerr << "unable to read and parse a double from standard input\n"; 
    exit(1); 
} 
...use my_double... 

값을 저장하기위한 ... 최고의 std::vector<double> 시작합니다 :

std::vector<double> my_doubles; 
my_doubles.push_back(my_double); 

// add all the doubles... 
double total = 0; 
for (auto& d : my_doubles) 
    total += d; 

이러한 것들을 결합의 예를 들면 다음과 같습니다

// read/store all the numbers from the current position in the input stream... 
while (std::cin >> my_double) 
    my_doubles.push_back(my_double); 

당신은 컨테이너를 정렬 할 수 있습니다를 유용 할 경우 :

std::sort(std::begin(my_doubles), std::end(my_doubles)); // default increasing 

std::sort(std::begin(my_doubles), std::end(my_doubles), // decreasing 
      [](double x, double y) { return x > y; }); 

다른 컨테이너 유형에서는 일부 작업이 더 쉬울 수 있습니다. 예를 들어 std::set<>은 중복 값을 거부하는 동안 정렬 된 값을 유지하는 편리한 방법이고 std::multiset은 중복을 저장할 수 있습니다.

0

Boost.Accumulators 프레임 워크를 사용하십시오. 종종 원하는 통계 연산 지연 열망 버전 모두를 제공

#include <iostream> 
#include <boost/accumulators/accumulators.hpp> 
#include <boost/accumulators/statistics/stats.hpp> 
#include <boost/accumulators/statistics/mean.hpp> 
#include <boost/accumulators/statistics/moment.hpp> 
using namespace boost::accumulators; 

int main() 
{ 
    // Define an accumulator set for calculating the mean and the 
    // 2nd moment ... 
    accumulator_set<double, stats<tag::mean, tag::moment<2> > > acc; 

    // push in some data ... 
    acc(1.2); 
    acc(2.3); 
    acc(3.4); 
    acc(4.5); 

    // Display the results ... 
    std::cout << "Mean: " << mean(acc) << std::endl; 
    std::cout << "Moment: " << accumulators::moment<2>(acc) << std::endl; 

    return 0; 
} 

프레임 워크가 정의 plethora of accumulators 있습니다

여기 선발 예이다. 예상대로 확장 성이 있습니다.

관련 문제