可能重复:
将未知类型的元素输入到向量中
程序应该从用户那里得到一个未知类型的元素列表,能够确定使用了哪种类型,能够对元素进行排序,并以新排序的顺序将它们打印回来。用户将输入元素的数量以及元素,它们必须都是相同的类型。
我对编程很陌生,对模板和向量也很陌生。任何对我一直在做错的事情的洞察力都值得赞赏。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int n;
vector<int>Integers;
vector<float>Floats;
vector<char>Chars;
vector<string>Strings;
template <class T>
//sorts vector elements
void sort(const T &x)
{
char *ptr1,*ptr2;
T tmp;
for (int i=0;i<n;i++)
{
ptr1=x[i];
for (int j=i+1;j<=n;n++)
{
ptr2=x[j];
if (tolower(ptr1)>tolower(ptr2))
{
tmp=x[j];
x[j]=x[i];
x[i]=tmp;
}
}
}
}
template <class T>
//prints vector in ascending order
void ascend(const T &x)
{
for (int z=0;z<n;z++)
{
cout<<x[z];
}
}
template <class T>
//prints vector in descending order
void descend(const T &x)
{
for (int z=n;z>=0;z--)
{
cout<<x[z];
}
}
template <class T>
//prints in both orders
void both(const T &x)
{
for (int z=0;z<n;z++)
{
cout<<x[z];
}
for (int z=n;z>=0;z--)
{
cout<<x[z];
}
}
int main()
{
int x=0, y=0;
string input;
cout<<"Number of elements: "<<endl;
cin>>n;
cout<<"Enter elements: "<<endl;
cin>>input;
//determines data type of first element inputed
for(int i=0;i<input.size();i++)
{
//int
if (input[i]>='0'&&input[i]<='9')
x=1;
//float
else if (input[i]=='.')
{
x=2;
i=input.size();
}
//char
else if (input[i]>='A'&&input[i]<='z')
x=3;
//string
if(input[i+1]>='A'&&input[i+1]<='z')
{
x=4;
i=input.size();
}
}
//populates vectors of various data types of size n
switch(x)
{
//int
case 1:
{
int a=1;
//creates vector of of size n+1
Integers.resize(n+1);
//concatenates first element
for (int i=0;i<input.size();i++)
{
a=(a*10)+input[i];
}
Integers[0]=a;
//adds in rest of elements
for (int i=1;i<=n;i++)
cin>>Integers[i];
sort(Integers);
break;
}
//float
case 2:
{
float b=1;
Floats.resize(n+1);
for (int i=0;i<input.size();i++)
{
if(input[i]!='.')
b=(b*10)+input[i];
else
{
i++;
for(int x=10,i;i<input.size();x*10,i++)
{
b+=input[i]/x;
}
}
}
Floats[0]=b;
for (int i=1;i<=n;i++)
cin>>Floats[i];
sort(&Floats);
break;
}
//char
case 3:
{
Chars.resize(n+1);
Chars[0]=input[0];
for (int i=1;i<=n;i++)
cin>>Chars[i];
sort(Chars);
break;
//string
}
case 4:
{
Strings.resize(n+1);
Strings[0]=input;
for (int i=1;i<=n;i++)
cin>>Strings[i];
sort(Strings);
break;
}
}
cout<<"Ascending (1), Descending (2), or Both (3)? ";
cin>>y;
//determines what vector is to be printed out and in what format
switch(y)
{
case 1:
{
switch(x)
{
case 1: ascend(Integers); break;
case 2: ascend(Floats); break;
case 3: ascend(Chars); break;
case 4: ascend(Strings); break;
}
}
case 2:
{
switch(x)
{
case 1: descend(Integers); break;
case 2: descend(Floats); break;
case 3: descend(Chars); break;
case 4: descend(Strings); break;
}
}
case 3:
{
switch(x)
{
case 1: both(Integers); break;
case 2: both(Floats); break;
case 3: both(Chars); break;
case 4: both(Strings); break;
}
}
}
return 0;
}