将字符串与数字进行比较,而无需编写太多运算符重载函数
compare string with a number without writing too many operator overloading functions
以下代码适用于将字符串与数字进行比较时"=="的情况(感谢πάντα ῥεῖ提供的解决方案)。">"、">="、"!="、"<"、"<="等呢? 是否可以通过编写函数模板来避免为每个运算符编写函数? 典型的函数模板是针对不同类型的相同操作,但我们对同一类型有不同的操作。
#include <unordered_map>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
bool operator==(const std::string& s, int i) {
int n = atoi(s.c_str());
return (n == i);
}
int main(int argc, char *argv[])
{
string t("1234");
printf("value is %sn", t.c_str());
if (t == atoi(argv[1])) {
printf("yesn");
} else {
printf("non");
}
}
谢谢。
我假设您有兴趣知道如何在不重载所有运算符的情况下提供将自定义类型与 int 相关的运算符。实现此目的的一种方法是提供对要与自定义类型关联的类型的隐式转换(在本例中为 int)。请参阅下面的示例。
#include <iostream>
using namespace std;
class Foo
{
public:
Foo(int val): _val(val)
{}
operator int()
{
return _val;
}
private:
int _val;
};
int main()
{
Foo foo(2);
cout << foo << endl;
cout << (foo == 2) << endl;
cout << (foo > 3) << endl;
}
这将产生:
2
1
0
现在,如果您只对字符串到整数的情况感兴趣,我只是建议使用 Boost lexical_cast,如 http://www.boost.org/doc/libs/1_58_0/doc/html/boost_lexical_cast/examples.html 中的此示例所示:
#include <boost/lexical_cast.hpp>
#include <vector>
int main(int /*argc*/, char * argv[])
{
using boost::lexical_cast;
using boost::bad_lexical_cast;
std::vector<short> args;
while (*++argv)
{
try
{
args.push_back(lexical_cast<short>(*argv));
}
catch(const bad_lexical_cast &)
{
args.push_back(0);
}
}
}
或者,如果您使用的是 C++11,只需遵循以下内容:std::lexical_cast - 有这样的事情吗?
"
>
、>=
、!=
、<
、<=
等呢?是否有可能通过编写函数模板来避免为每个运算符编写函数?
这听起来像是一个XY问题。
重载所有可能的比较运算符std::string
是解决此问题的错误方法。
如果要对作为字符串给出的数字应用数值比较操作,只需将字符串转换为数字一次,然后对转换后的值应用比较,而不是用std::string
覆盖每个可能的比较操作:
try {
int i = stoi(argv[1]); // <<< convert once!
if (i == 1234) { // Use numeric comparison operators ...
// ... in any way you like:
// if (i <= 1234) {
// if (i >= 1234) {
// if (i < 1234) {
// if (i != 1234) {
// ....
printf("yesn");
} else {
printf("non");
}
}
catch(const std::exception& ex) {
// conversion to number failed
}
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 错误:字符数组的初始值设定项太多
- 对象实例化调用构造函数的次数太多
- Levenshtein 两个文件的距离花费了太多时间
- 我有三个 getline,但是一旦编译,输入就太多了
- 将使用太多的纹理插值器 - 带旋转的着色器
- C/C++:socket() 创建在循环中失败,打开的文件太多
- 使用Visual Studio在虚幻引擎中创建一个新的类c ++给了我太多的错误
- C++:数组<>初始值设定项太多
- GLib-ERROR:为GWakeup创建管道:打开的文件太多
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 我会导致太多内存泄漏,以至于我的计算机无响应吗?
- ZeroMq:打开的文件太多.在同一对象上连续增长的fd使用数
- 将字符串与数字进行比较,而无需编写太多运算符重载函数
- 重载运算符<<:此运算符函数的参数太多
- 函数调用运算符重载的参数太多
- 重载运算符的参数太多,visual studio c++
- 这个函数的运算符参数太多
- 重载<<运算符错误C2804:二进制'运算符<<'参数太多
- 在类中创建运算符+而不声明太多不必要的变量的最佳方法