这样,我可以找到数组中元素的数量。但是,当我将此int数组作为模板作为参数时,结果计算不正确
int arr[] = {1,2,3,4,5};
int size_arr = sizeof(arr) / sizeof(arr[0]);
我将INT数组作为类型模板的参数添加到列表中。template <typename listType, typename arrayX>
listType addList(listType e , arrayX array)
{
int sizeOf = sizeof(array);
int sizeOfperOne = sizeof(array[0]);
int arrSize = sizeOf / sizeOfperOne ;
cout << "Total Byte : " << sizeOf << " BytePerUnit : " << sizeOfperOne << " arrSize : " << arrSize<< endl;
for (int i = 0; i < arrSize; i++)
{
e.push_back(array[i]);
}
return e;
}
并创建了另一个模板和方法来打印此列表内容template <typename T>
void print(T& t, string name)
{
typename T::iterator i = t.begin();
cout << name << "\tMembers ==>>> ";
while (i != t.end())
{
if (i == t.begin())
{
cout << *i++;
}
else
{
cout << " - " << *i++;
}
}
cout << endl;
}
int main()
{
int mlArray[] = { 1,2,3,4,5};
list<int> MasterListe ;
MasterListe = addList(MasterListe, mlArray);
cout << "MasterListe SizeOf : " << MasterListe.size() << endl;
print(MasterListe, "MasterList : ");
return 0;
}
Total Byte : 8 BytePerUnit : 4 arrSize : 2
MasterListe SizeOf : 2
MasterList : Members ==>>> 1 - 2
数组用数字1,2,3,4,5填充,尽管传递了5个单位,但返回值为1和2。
我可能还想从下面的类中以INT类型创建当前正在使用的列表。
list<TradeList>
class TradeList
{
public:
int PosTicket ;
strinh Pairs ;
double OpenPrice ;
double StopLoss ;
double TakeProfit ;
}
相信我,我无法通过研究找到解决方案。非常感谢你的帮助。
最佳答案
主要问题是数组会衰减到指针,因此模板函数sizeof()
中的addList
值实际上正在尝试获取sizeof(int *)
。
如果addList
所做的只是在std::list
中添加项目,则有通用的方法可以执行此操作而无需创建另一个函数。
一种方法是使用std::copy_n:
#include <iostream>
#include <list>
#include <algorithm>
#include <iterator>
#include <string>
class TradeList
{
public:
int PosTicket ;
std::string Pairs ;
double OpenPrice ;
double StopLoss ;
double TakeProfit ;
};
int main()
{
TradeList mlArray[5];
std::list<TradeList> MasterListe;
std::copy_n(mlArray, std::size(mlArray), std::inserter(MasterListe, MasterListe.end()));
std::cout << MasterListe.size();
}
输出:5
关于c++ - C++模板参数sizeof返回错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64840532/