我创建了一个带有私有向量的类,它使用std::string作为其数据类型。
#pragma once
#include <string>
#include <vector>
#include <iostream>
class Pokemon {
public:
//Constructor - leaving it here for reference
Pokemon(std::string name, int LVL, int HP, int ATK, int DEF, int SPATK, int SPDEF, int SPD,
std::vector<std::string>moves, std::vector<int>PP);
//Member Functions
std::vector<std::string> getMoves();
private:
std::vector<std::string>moves;
};
为了从这个向量中检索信息,我创建了一个名为getMoves()的公共类函数,它应该从该向量返回所有信息。下面是我在.cpp文件中编写的函数定义。
std::vector<std::string> Pokemon::getMoves() {
return moves;
}
在尝试打印带有std::cout这些移动的向量并收到“”错误后,我意识到必须重载<<操作符。
关于如何重载<<操作符,我有几个问题,这样我的向量就会打印出来。
std::vector<std::string>
我很感谢你对这些问题的帮助,谢谢!
发布于 2019-03-12 07:00:50
下面的示例将重载每个向量的<<
运算符。如果要为特定向量指定输出,则创建包装器结构或类。
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
ostream& operator<<(ostream& os, const vector<T>& v)
{
os << "[";
for (int i = 0; i < v.size(); ++i) {
os << v[i];
if (i != v.size() - 1)
os << ", ";
}
os << "]\n";
return os;
}
现在,当您想要像这样打印向量时:
int main() {
vector<int> a = {0, 1, 2};
cout << a << endl;
}
它将打印以下结果:[0, 1, 2]
发布于 2019-03-12 08:25:41
#include <iostream>
#include <vector>
#include <map>
// Helper Function to Print Test Containers (Vector and Map)
template <typename T, typename U>
std::ostream& operator<<(std::ostream& out, const std::pair<T, U>& p) {
out << "[" << p.first << ", " << p.second << "]";
return out;
}
template <template <typename, typename...> class ContainerType, typename
ValueType, typename... Args>
void print_container(const ContainerType<ValueType, Args...>& c) {
for (const auto& v : c) {
std::cout << v << ' ';
}
std::cout << '\n';
}
正如NutCracker提到的,在几乎所有类型的容器中,operator <<
重载都是您最好的朋友。除了他的好答案外,这里还有一个模板化分辨率的扩展版本,用于打印所有类型的STL容器。
基本上,除了向量之外,对对类型的容器来说也是超载。作为一个例子。ValueType -> First or only Element in container template
和Args... variadic template as rest of the elements in container
(第二个或多个元素)对于pair <T,U>
基本映射-无序映射-您只有第一个和第二个元素到overload
,您可以将此技术应用于几乎所有容器类型。如果您只想打印每个口袋妖怪特性而不调用任何额外的函数pokemon::getMoves()
,您也可以overload << for pokemon class
,也许最好只打印一个口袋妖怪等等。
friend
允许私人和公共成员访问
friend ostream& operator<< (ostream& os, const Pokemon& pokemonobj) {
os << print_container(pokemonobj.getMoves());
return os;
}
https://stackoverflow.com/questions/55124332
复制相似问题