우리가 STL과 C++을 사용한다면 말하자면 현대적인 스타일로 쓰고 실제로 STL을 사용하십시오.
현대 C++ (11) 사용 문제에서 내 시도 : 합계에 그것은 각각의 하위 배열 합계를 누적 사용
#include <vector>
#include <iostream>
#include <algorithm>
typedef std::vector<int> ArrayInt;
typedef std::vector< std::vector<int> > ArrayData;
bool compare(const ArrayInt& a, const ArrayInt& b) {
std::cout << &(a) << ' ' << &(b) << std::endl;
int sumA = std::accumulate(a.begin(), a.end(), 0);
int sumB = std::accumulate(b.begin(), b.end(), 0);
return sumA < sumB;
}
int main(int argc, char** argv) {
ArrayData array = {
{1,2,4,0,3,7,6,8,3,3},
{13,2,4,0,3,7,6,8,3,3},
{10,2,4,0,3,7,6,8,3,3},
{1,2,4,0,3,7,6,8,3,3},
{16,2,4,0,3,7,6,8,3,3},
{1,2,400,0,3,7,6,8,3,3},
{1,2,4,0,3,7,6,8,3,3},
{120,2,4,0,3,7,6,8,3,3},
{1,2,4,0,3,7,6,8,3,3},
{1,2,4,0,3,7,6,8,3,3}
};
std::sort(array.begin(), array.end(), compare);
for (auto row : array) {
for (int num : row)
std::cout << num << ' ';
std::cout << std::endl;
}
}
및 종류 ..이 같은 행 합계를 가지고 있기 때문에 매우 비효율적이다 여러 번 ..하지만 그냥 사용자 정의 비교 기능을 과시하는 것입니다.
는 연습으로, 나는 정렬하기 전에, 합산을 할 가능한 모든 코어에 걸쳐 합산 일부를 배포하는 비동기를 사용하여이 버전을 썼다. 나는 그것이 주제에서 조금 벗어나고있어 미안해. 나는 어떤 사람들은 여전히 유용 희망 :
그것은 pthread와 라이브러리 또는 유사한 컴파일 할 필요가
#include <vector>
#include <iostream>
#include <algorithm>
#include <future>
typedef std::vector<int> IntRow;
typedef std::pair<int, IntRow> DataRow;
typedef std::vector<DataRow> DataTable;
int main(int argc, char** argv) {
// Holds the sum of each row, plus the data itself
DataTable array = {
{0, {1,2,4,0,3,7,6,8,3,3}},
{0, {13,2,4,0,3,7,6,8,3,3}},
{0, {10,2,4,0,3,7,6,8,3,3}},
{0, {1,2,4,0,3,7,6,8,3,3}},
{0, {16,2,4,0,3,7,6,8,3,3}},
{0, {1,2,400,0,3,7,6,8,3,3}},
{0, {1,2,4,0,3,7,6,8,3,3}},
{0, {120,2,4,0,3,7,6,8,3,3}},
{0, {1,2,4,0,3,7,6,8,3,3}},
{0, {1,2,4,0,3,7,6,8,3,3}}
};
// Make use of multiple cores if it's efficient enough
// get the sum of each data row
std::vector<std::future<int>> sums(array.size());
auto next = sums.begin();
for (auto& row : array)
*next++ = std::async([](const IntRow& row) { return std::accumulate(row.begin(), row.end(), 0); }, row.second);
// Get the results
auto nextRow = array.begin();
for (auto& sum: sums)
(*nextRow++).first = sum.get();
// Sort it
std::sort(array.begin(), array.end(),
[](const DataRow& a, const DataRow& b) { return a.first < b.first; });
// Print it
for (auto row : array) {
for (int num : row.second)
std::cout << num << ' ';
std::cout << std::endl;
}
}
: std::sort
이 유형 T
의 요소의 컨테이너에서 호출
g++ -O6 sort.cpp --std=c++11 -g -lpthread
당신은 당신의 비교 함수는 두 개의 함수 포인터를 소요 깨닫는다 : 가장 쉬운 방법은 (여기서 유연한 외부 치수)
std::array<T, N>
가 사용하는 정적 크기의 배열을 정렬하려면? –cdecl 상태 : "int 배열 10에 대한 포인터로 선언"int, 크기 10의 배열에 대한 포인터입니다. –
소스를 인용 할 수 있습니까? 10 int의 배열에 대한 포인터는 const int (* a) [10]이 아닌 const int * a [10]이어야합니다. –