开发者

C++ design: container of instances and pointers

开发者 https://www.devze.com 2022-12-26 14:41 出处:网络
I\'m wondering something. I have class Polygon, which composes a vector of Line (another class here) class Polygon

I'm wondering something.

I have class Polygon, which composes a vector of Line (another class here)

class Polygon
{
 开发者_如何学JAVA std::vector<Line> lines;

public:
  const_iterator begin() const;

  const_iterator end() const;

}

On the other hand, I have a function, that calculates a vector of pointers to lines, and based on those lines, should return a pointer to a Polygon.

 Polygon* foo(Polygon& p){

  std::vector<Line> lines = bar (p.begin(),p.end());

  return new Polygon(lines);

 }

Here's the question:

I can always add a Polygon (vector

Is there a better way than dereferencing each element of the vector and assigning it to the existing vector container?

//for line in vector<Line*> v
//vcopy is an instance of vector<Line>
vcopy.push_back(*(v.at(i))

I think not, but I don't really like that approach.

Hopefully, I will be able to convince the author of the class to change it, but I can't base my coding right now to that fact (and I'm scared of a performance hit).

Thanks in advance.


You can transform() the container:

struct deref { // NO! I don't want to derive, LEAVE ME ALONE!
    template<typename P>
    const P& operator()(const P* const p) const { return *p; }
};

// ...
    vector<Line*> orig; // assume full ...
    vector<Line> cp(orig.size());
    transform(orig.begin(), orig.end(), cp.begin(), deref());


It depends how often you need to do that and how specifically. There is such a thing as a transforming iterator, and you could make one such that

vcopy( deref_iter( v.begin() ), deref_iter( v.end() ) );

would do what you want. However, that's not that much easier than what you have, and a straightforward function taking a pointer-vector and returning an object-vector would be easier to implement and to use.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号