Сохранение (x, y) точки в массив

Поэтому я пытаюсь сохранить точку в массиве. Массив должен иметь размер 10, а точки должны быть случайным числом от 0 до 100. Я собираюсь использовать этот массив, а затем организовать его посредством быстрой сортировки и выяснить, какие точки находятся ближе всего друг к другу. Проведя некоторые исследования, я обнаружил, что у класса Utility есть кое-что, что, я думаю, будет работать, поэтому я пытаюсь выяснить, как заставить массив генерироваться со случайными точками. Во-первых, мне нужно, чтобы массив передавался по ссылке или как-то иначе, просто чтобы убедиться, что я могу иметь этот массив в main.

#include <iostream>
#include "qsort.h"#include <stdlib.h>
#include <utility>

using namespace std;

const int ARRAY_SIZE = 10;

void initializePairs(pair<int,int> array);

int main()
{
//pair<int, int> shortPointArray[ARRAY_SIZE];
/*pair<int,int> temp = make_pair(5,6);
pair<int,int> shortPointArray[1];
shortPointArray[0] = temp;*/

pair<int,int> shortPointArray[1];
//qsort sorting;

initializePairs(shortPointArray);

return 1;
}

void initializePairs(pair<int,int> array)
{
int x;
int y;
pair<int,int> temp;

for(int i = 0; i < ARRAY_SIZE; i++)
{
x = rand() % 100;
y = rand() % 100;
temp = make_pair(x,y);
array[i] = temp;
}
}

0

Решение

Не так сложно сделать то, что вы ищете:

main.cpp

#include <iostream>
#include <vector>
#include <algorithm>
#include <random>

#include "Point.h"
int main() {
std::random_device rd; // Random Device: Used To Seed Mersenne Random Generator
std::mt19937 gen;      // Mersenne Twister
gen.seed( rd() );      // Seed The Generator
std::uniform_int_distribution<> dist(0, 100); // Uniform Int Distribution between [a, max]

// Point<int>
std::vector<Point<int>> points;
points.reserve( NUM_POINTS );

for ( std::size_t i = 0; i < NUM_POINTS; i++ ) {
// Instead of creating a temporary stack copy each iteration
// I chose to use the constructor directly and instead of
// push_back, I'm using emplace_back.
// Point<int> p( dist( gen ), dist( gen ) );
// points.push_back( p );

points.emplace_back( Point<int>( dist( gen ), dist( gen ) ) );
}

std::cout << "Showing 10 points of type int with random (x,y):\n";
for ( auto& p : points ) {
std::cout << p;
}
std::cout << std::endl;

// Point<float>
std::vector<Point<float>> points2;
points.reserve( NUM_POINTS );
std::uniform_real_distribution<float> dist2( 0, 100.0f );

for ( std::size_t i = 0; i < NUM_POINTS; i++ ) {
// Instead of creating a temporary stack copy each iteration
// I chose to use the constructor directly and instead of
// push_back, I'm using emplace_back.
// Point<float> p( dist( gen ), dist( gen ) );
// points2.push_back( p );

points2.emplace_back( Point<float>( dist( gen ), dist( gen ) ) );
}

std::cout << "Showing 10 points of type float with random (x,y):\n";
for ( auto& p : points2 ) {
std::cout << p;
}
std::cout << std::endl;

// Sorting the containers:
std::sort( points.begin(), points.end() );
std::sort( points2.begin(), points2.end() );

std::cout << "Showing the sorted points with type int (x,y):\n";
for ( auto& p : points ) {
std::cout << p;
}
std::cout << std::endl;

std::cout << "Showing the sorted points with type float (x,y):\n";
for ( auto& p : points2 ) {
std::cout << p;
}
std::cout << std::endl;std::cout << std::endl;
system( "PAUSE" );
return 0;
}

Point.h

#ifndef POINT_H
#define POINT_H

#include <iostream>
#include <tuple>     // std::tie

const std::size_t NUM_POINTS { 10 };

// Need class Point prototype for operator<< declaration
template<class> class Point;

// Need operator<< declaration for class template Point's friend declaration
template<class T>
std::ostream&  operator<<( std::ostream& out, const Point<T>& );

// Class Declaration & Definition
template<class T>
class Point {
public:
T _x;
T _y;
Point() : _x( 0 ), _( 0 ) {}
Point( T x, T y ) : _x( x ), _y( y ) {}
Point( T& x, T& y ) : _x( x ), _y( y ) {}
Point( T* x, T* y ) : _x( *x ), _y( *y ) {}

// friend prototype: notice the extra <> in this declaration
// It tells the compiler that this friend function will be a specialization of this class template
friend std::ostream& operator<< <>( std::ostream& out, const Point<T>& p );

// operator< for comparison
bool operator<( Point<T>& p ) {
// std::tie makes it real easy to compare a (set) of values.
return std::tie( _x, _y ) < std::tie( p._x, p._y );
}

// operator> for comparison
bool operator<( Point<T>& p ) {
return !(*this < p );
}

// operator== for comparison
bool operator==( Point<T>& p ) {
return (this->_x == p._x && this->y == p._y );
}
};

// operator<< definition
template<class T>
std::ostream& operator<<( std::ostream& out, const Point<T>& p ) {
return out << "(" << p._x << "," << p._y << ")\n";
}

#endif // !POINT_H

Что касается реализации класса template Point<T> Вы можете обратиться к комментариям в заголовочном файле.


Для деталей основной функции я перейду к некоторым из этих деталей.

Для генерации случайных значений я бы рекомендовал держаться подальше от random() или любой из связанных с ним устаревших или скоро будет функционировать. Я бы начал с изучения и использования псевдослучайных генераторов, которые можно найти в стандартной библиотеке вместе с различными типами распределений: все они можно найти в <random> заголовочный файл Ты можешь использовать std::default_random_engine() но я предпочитаю использовать std::random_device Мы можем использовать это, чтобы SEED двигатель (генератор) по нашему выбору. Один из наиболее популярных двигателей или генераторов известен как Mersenne Twister который std::mt19937 и есть 65-битная версия этого тоже. Это довольно просто сделать.

{
std::random_device rd; // create an instance of our device to seed with
std::mt19937 gen;      // create an instance of our generator (engine)
gen.seed( rd() ); // This seeds the generator (engine)
// Now we need a distribution along with its data type
// there are different versions of these distributions for different types
// Some are for integral types while others are for floating point types

// Here we want a uniform distribution for int so we default the template
std::uniform_int_distribution<> dist(0, 100); //random from [0,100]
// otherwise we could of done
std::uniform_int_distribution<unsigned int> dist2( 0, 50 ); // random from [0, 50]

// There are other types of distributions
std::normal_distribution<> a;
std::poisson_distribution<> b;
// etc.

// If the distributions say "real" they are floating point types
std::uniform_real_distribution<float> f;
std::uniform_real_distribution<double> d;

// Just as there are different distributions there also other
// generators or engines beside the mersenne twister.

// There is another way besides using `random_device` to seed the generator
// you can use <chrono> header to use `std::chrono::high_resolution_clock
// to seed the generator
// You can also seed by const value
// and you can use std::seed_seq;
}

Вы можете найти всю информацию, которая вам нужна для выполнения псевдослучайных генераторов & Распределения от этот страница интернета.


Так что теперь, когда у нас есть наши случайные генераторы и работают следующий шаг, мы объявляем std::vector<Point<int>> тогда мы используем его reserve функционировать и установить его с нашей константой NUM_POINTS, Затем мы проходим цикл for NUM_POINTS итерации и мы заполняем наш контейнер случайным (x,y) набор значений.
Затем мы отображаем результаты, используя ранжированную базу для цикла.

Я повторяю вышеописанный процесс, чтобы показать, что это делается с помощью float. Я сделал это таким образом, чтобы показать полезность шаблонов.

После этого я, наконец, сортирую контейнеры, просто позвонив std::sort( begin, end ) используя итераторы вектора. Затем я возвращаюсь и использую ранжированную базу для цикла, чтобы показать оба отсортированных вектора.

использование std :: sort работает очень легко, так как мы определили перегруженный operator<() для нашего класса, и мы использовали std :: tie, чтобы легко сравнить их. Это показывает вам мощь стандартной библиотеки, объединяя кучу частей, таких как набор Legos!

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector