1

在我的示例中,我想打印三个相似的向量。你能帮我理解如何将向量转移到子程序中,以免重复自己吗?

#include "stdafx.h";
#include <vector>;
#include <iostream>
#include <algorithm>
#include <iterator>

using namespace std;


struct SPoint
{   
    int X;
    int Y;
};

vector<SPoint> points;
vector<SPoint> selected;
vector<SPoint> cleared;

void print_points()
{
    cout << "Points: "<< endl;
    for (int i = 0; i < points.size(); i++)
    {
        cout << '('<<points[i].X <<',' <<points[i].Y <<')'<< endl;
    }
    cout << endl;
}

void print_selected()
{
    cout << "Selected: "<< endl;
    for (int i = 0; i < selected.size(); i++)
    {
        cout << '('<<selected[i].X <<',' <<selected[i].Y <<')'<< endl;      
    }
    cout << endl;
}

void print_cleared()
{
    cout << "Cleared: "<< endl;
    for (int i = 0; i < cleared.size(); i++)
    {
        cout << '('<<cleared[i].X <<',' <<cleared[i].Y <<')'<< endl;        
    }
    cout << endl;
}



int main ()
{
    SPoint temp = {0, 0};

    for (int i = 0; i < 11;i++)
    {
        temp.X = i;
        temp.Y = i;
        points.push_back(temp);

    }

    for (int i = 5; i< 11;i++)
    {
        temp.X = i;
        temp.Y = i;
        points.push_back(temp);
    }

    print_points();
    print_selected();
    print_cleared();

    system ("pause");

  return 0;
}
4

4 回答 4

1

你可以这样做:

void
print(const std::vector<SPoint>& vect, const std::string& message)
{
    std::cout << message << ":" << std::endl;
    for (int i = 0, size = vect.size(); i < size; ++i)
        std::cout << vect[i].X << ":" << vector[i].Y << " ";
    std::endl;
}

print(points, "Points");
print(points, "Selected");
print(points, "Cleared");

祝你好运

于 2013-01-05T20:59:18.313 回答
0

要将向量作为参数传递给函数,您可以执行以下操作:

void func(const vector<SPoint>& points) {
  ... do stuff
}

然后你在你的代码中调用这个函数,如下所示:

  ...some stuff
  vector<SPoint> a;
  func(a);
于 2013-01-05T20:57:10.753 回答
0

只需使用const对向量的引用并将其传递给函数:

void print(const vector<SPoint> &data) const {

}

...

print(points);
于 2013-01-05T20:57:50.457 回答
0

这是一个完整的C++风格的方法:

struct SPoint
{   
    int X;
    int Y;
};

std::ostream& operator <<( std::ostream& stream, SPoint const& point )
{
    stream << '(' << point.X << ',' <<point.Y << ')';
    return stream;
}

void print_vector( std::ostream& stream, std::vector< SPoint > const& vector )
{
    std::copy(
        points.begin(), points.end()
      , std::ostream_iterator< SPoint >( std::cout, '\n' )
    );
}

接着:

print_vector( std::cout, points );
print_vector( std::cout, selected );
print_vector( std::cout, cleared );
于 2013-01-05T21:00:31.720 回答