gpt4 book ai didi

c++ - 如何添加两个多维 std::vectors(不使用运算符)?

转载 作者:行者123 更新时间:2023-11-30 01:40:08 29 4
gpt4 key购买 nike

算法简单明了:
继续将 n 维 vector 分解为 n-1 维组成 vector ,直到您可以访问 basic-datatype 对象。它们的添加简单且定义明确。

这是我使用模板和 operator+ 的实现:

#include <iostream>
#include <vector>

template<class T>
std::vector<T> operator+ (const std::vector<T>& v1, const std::vector<T>& v2)
{
std::vector<T> output;
unsigned len = v1.size();
output.resize(len);
for (int i = 0; i < len; ++i)
output[i] = v1[i] + v2[i];
return output;
}

int main ()
{
using namespace std;

vector<std::vector<int>> x = {{8,9,0},{5,6,7}};
vector<std::vector<int>> y = {{1,1,1},{1,1,1}};

auto result = x + y; // Yeah, just like that !

// Being Lazy, instead of implementing multi-dimensional vector printing...
for (int i = 0; i < result.size(); ++i)
{
for (int j=0; j<result[i].size(); ++j)
cout << result.at(i).at(j) << " ";
cout << "\n";
}

return 0;
}

但假设您不允许使用operator+
您必须将接口(interface)设计为某些函数 Add()

可是我做不到!!这是我的尝试:

#include <iostream>
#include <vector>

// Hoping to handle vectors...
template<class T>
std::vector<T> Add (const std::vector<T>& v1, const std::vector<T>& v2)
{
std::vector<T> output;
unsigned len = v1.size();
output.resize(len);
for (int i = 0; i < len; ++i)
output[i] = Add(v1[i], v2[i]);
return output;
}

// Hoping to handle basic-datatypes...
template<class T>
T Add (const T& v1, const T& v2)
{
T output;
unsigned len = v1.size();
output.resize(len);
for (int i = 0; i < len; ++i)
output[i] = v1[i] + v2[i];
return output;
}

int main ()
{
using namespace std;

vector<std::vector<int>> x = {{8,9,0},{5,6,7}};
vector<std::vector<int>> y = {{1,1,1},{1,1,1}};

auto result = Add(x, y); // I wish ! But not happening !

// Being Lazy, instead of implementing multi-dimensional vector printing...
for (int i = 0; i < result.size(); ++i)
{
for (int j=0; j<result[i].size(); ++j)
cout << result.at(i).at(j) << " ";
cout << "\n";
}

return 0;
}

有可能吗?

最佳答案

您必须为 Add() 提供适用于基本数据类型的版本

// Handle basic-datatypes
template<class T>
T Add(const T& x1, const T& x2)
{
return x1 + x2;
}

// Specialisation for vectors
template<class T>
std::vector<T> Add(std::vector<T> const& v1, std::vector<T> const& v2)
{
assert(v1.size()==v2.size());
std::vector<T> result;
result.reserve(v1.size());
for(size_t i=0; i!=v1.size(); ++i)
result.emplace_back(Add(v1[i],v2[i])); // possibly recursive
return result;
}

关于c++ - 如何添加两个多维 std::vectors(不使用运算符)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44007409/

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