我使用大量坐标向量编写了一个迷宫程序。测试一个100x100网格,当我使用vector<int>
时,程序花了383秒,但是当我使用pair<int,int>
时,只花了13秒。这种戏剧性的加速从何而来?
以下是代码:(仍有待改进)
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <algorithm>
#include <utility>
using namespace std;
const int HEIGHT = 100, WIDTH = 100;
bool in_bounds(int x, int y)
{
// Cells (0,0) to (WIDTH-1, HEIGHT -1)
return (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT);
}
bool in_vector(int x, int y, vector<pair<int,int> > v)
{
return find(v.begin(), v.end(), pair<int,int>(x,y)) != v.end();
}
vector<string> get_dir(int x, int y, vector<pair<int,int> > v)
{
vector<string> open_dir; // Open neighbor cells
if (in_bounds(x+1,y) && !in_vector(x+1,y,v))
open_dir.push_back("e");
if (in_bounds(x-1,y) && !in_vector(x-1,y,v))
open_dir.push_back("w");
if (in_bounds(x,y+1) && !in_vector(x,y+1,v))
open_dir.push_back("n");
if (in_bounds(x,y-1) && !in_vector(x,y-1,v))
open_dir.push_back("s");
return open_dir;
}
int main()
{
vector<pair <int,int> > in_maze_cells {make_pair(0, 0)}, path {make_pair(0, 0)};
vector<vector<string> > hor_walls (WIDTH, vector<string>(HEIGHT, "--")),
vert_walls (WIDTH, vector<string>(HEIGHT, "|"));
srand(time(0));
while (in_maze_cells.size() != HEIGHT * WIDTH)
{
pair <int,int> current_cell = path.back();
int x = current_cell.first;
int y = current_cell.second;
vector<string> open_dir = get_dir(x, y, in_maze_cells);
if (open_dir.size())
{
// Randomly pick an open cell and move to it
string dir = open_dir[rand() % open_dir.size()];
pair<int,int> new_cell;
// Left and bottom wall coordinates match cell coordinates
if (dir == "e"){
new_cell = make_pair(x+1,y);
vert_walls[x+1][y] = " ";
}
if (dir == "w"){
new_cell = make_pair(x-1,y);
vert_walls[x][y] = " ";
}
if (dir == "n"){
new_cell = make_pair(x,y+1);
hor_walls[x][y+1] = " ";
}
if (dir == "s"){
new_cell = make_pair(x,y-1);
hor_walls[x][y] = " ";
}
in_maze_cells.push_back(new_cell);
path.push_back(new_cell);
}
else
path.pop_back(); // Backtracking
}
// Top row
for(int i=0; i<WIDTH; i++)
cout << "+--";
cout << "+" << endl;
for(int i=HEIGHT-1; i>=0; i--)
{
for(int j=0; j<WIDTH; j++)
cout << vert_walls[j][i] << " ";
cout << "|" << endl;
for(int j=0; j<WIDTH; j++)
cout << "+" << hor_walls[j][i];
cout << "+" << endl;
}
return 0;
}
答案 0 :(得分:4)
矢量矢量可能更重,因为矢量比一对更复杂。
此外,在您的函数中,您按值传递该向量:
bool in_vector(int x, int y, vector<cell> v)
{
return find(v.begin(), v.end(), cell(x,y)) != v.end();
}
这使得它的成本更高。将其更改为
bool in_vector(int x, int y, vector<cell> const& v)
如果您有兴趣,我可以提供更多优化提示