gpt4 book ai didi

c++ - 具有 C++ 迭代器参数的多功能函数

转载 作者:行者123 更新时间:2023-12-01 13:12:41 26 4
gpt4 key购买 nike

我正在使用通过迭代器接受范围的函数,类似于以下代码中的“printPoints”和“printPoints2”。到目前为止,“printPoints”可以接受 Point 对象的 vector/列表/等的迭代器,但需要“printPoints2”来处理指向 Point 对象的指针的 vector/列表/等。有什么技巧可以编写一个更通用的函数来替换这两个函数吗?

提前致谢。

#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <memory>

struct Point {
int x;
int y;

Point(int x, int y): x(x), y(y) {}
};

/*
Is there a more versatile function to replace the following two?
*/
template <class Iter>
void printPoints(Iter begin, Iter end) {
for(auto it=begin; it!=end; ++it)
std::cout << "{" << it->x << " " << it->y << "}";
}
template <class Iter>
void printPoints2(Iter begin, Iter end) {
for(auto it=begin; it!=end; ++it)
std::cout << "{" << (*it)->x << " " << (*it)->y << "}";
}

int main()
{
std::vector<Point> vecPoints = {{0,0}, {1,1}};
std::cout << "vector of points: ";
printPoints(vecPoints.begin(), vecPoints.end());
std::cout << "\n";

std::list<Point> listPoints = {{2,2}, {3,3}};
std::cout << "list of points: ";
printPoints(listPoints.begin(), listPoints.end());
std::cout << "\n";

std::vector<std::unique_ptr<Point>> vecPtrPoints;
vecPtrPoints.push_back(std::make_unique<Point>(4,4));
vecPtrPoints.push_back(std::make_unique<Point>(5,5));
std::cout << "vector of pointers to point: ";

// won't work because of "it->x" inside the function
//printPoints(vecPtrPoints.begin(), vecPtrPoints.end());
printPoints2(vecPtrPoints.begin(), vecPtrPoints.end());
std::cout << "\n";
}

最佳答案

C++17 助你一臂之力!

#include <type_traits>

template <class Iter>
void printPoints(Iter begin, Iter end) {
for(auto it=begin; it!=end; ++it)
{
if constexpr (std::is_same_v<typename std::iterator_traits<Iter>::value_type, Point>)
{
std::cout << "{" << it->x << " " << it->y << "}";
}
else
{
std::cout << "{" << (*it)->x << " " << (*it)->y << "}";
}
}
}

如果你没有 c++17 那么你可以通过使用 std::enable_if 来实现类似的东西,让你有两个 printPoints 函数来同名。

另一种方法是重构您的代码:

void printPoint(const Point& point)
{
std::cout << "{" << point.x << " " << point.y << "}";
}

void printPoint(const std::unique_ptr<Point>& point)
{
printPoint(*point);
}

template <class Iter>
void printPoints(Iter begin, Iter end) {
for(auto it=begin; it!=end; ++it)
{
printPoint(*it);
}
}

这有点冗长,但适用于早期的 c++ 标准,对于新手 c++ 程序员来说可能更容易理解。

选项 3 是两者的结合:

void printPoint(const Point& point)
{
std::cout << "{" << point.x << " " << point.y << "}";
}

template <class Iter>
void printPoints(Iter begin, Iter end) {
for(auto it=begin; it!=end; ++it)
{
if constexpr (std::is_same_v<typename std::iterator_traits<Iter>::value_type, Point>)
{
printPoint(*it);
}
else
{
printPoint(**it);
}
}
}

关于c++ - 具有 C++ 迭代器参数的多功能函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com