求 C++ 一道 简单的 STL 和 一道 简单的 关于 “模板”的示范 程序

2025-03-05 03:09:09
推荐回答(2个)
回答1:

#include
#include
#include
#include

struct Show_Message {
void show() { printf("Welcome!\n"); }
};
extern Show_Message display;
template class Container, unsigned int Size, Show_Message& _disob>
struct Run {
protected:
typedef Container > container_type;
container_type mem;
public:
Run() :mem(Size) { _disob.show(); }
};

struct Exit { int exit() const throw() { return 0; } };

template struct exit_procedure {
int exit_ok() {
const Exit* p = new Exit;
if ((p->*f)())
return (p->*f)() - 1;
else
delete p;
return (p->*f)();
}
};

template int exit_procedure<&Exit::exit>::exit_ok();

int main()
{
const char str[13] = "Hello world\n";
std::for_each(&str[0],&str[12],std::pointer_to_unary_function(std::putchar));
Run object;

return (new exit_procedure<&Exit::exit>)->exit_ok();
}

这个程序无聊得很,但是template的基本用法差不多都有了——除了template中的export关键字,因为export根本没有几个编译器会支持

回答2:

//简单的 STL
vector a;
a.push_back(3);
a.push_back(4);
a.push_back(5);
a.push_back(6);
find(a.begin(), a.end(), 4); //true
find(a.begin(), a.end(0, 5); false;
a.erase(find(a.begin(), a.end(), 40, a.end()); //删除4.

//模板”的示范 程序
template
class Test
{
T *a;
}