模拟python的“输入"在C ++中 [英] Simulating python's "in" in C++
本文介绍了模拟python的“输入"在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我设法弄清了python中的确切语法(检查容器中是否存在值),因此您可以只检查值是否在任何支持begin()
/end()
方法的容器中.
I managed figure out exact syntax like in python (checking if value is present in container), so you can just check if value is "in" any container that supports begin()
/end()
methods.
这是我的实现方式
#include <algorithm>
#include <iostream>
#include <vector>
template<class T>
struct specified {
specified(T const& value) : value_(value) {}
T value_;
template<class Container>
bool operator * (Container const& cont) {
return (std::find(cont.begin(), cont.end(), value_) != cont.end());
}
};
struct general {
template<class T>
friend specified<T> operator *(T const& rhs, general const&) {
return specified<T>(rhs);
}
};
#define in * general() *
int main() {
std::vector<int> vec{1,2,3};
std::cout << 1 in vec << std::endl;
std::cout << 4 in vec << std::endl;
}
我的问题是,它有什么陷阱吗?安全吗?
My question is, does it have any pitfalls? Is it safe?
推荐答案
对于字符串,它有一个小的解决方法.
It has a small workaround for strings.
在使用字符串文字时无法正常工作.
Doesn't work as expected with string literals.
std::vector<string> vec{"1","2","3"};
std::cout << "1" in vec << std::endl;
std::cout << "4" in vec << std::endl;
此代码会导致编译时错误.
This code results in compile-time error.
error: array used as initializer
specified(T const& value) : value_(value) {}
C ++将字符串文字作为char[]
,而不是将其作为string
.因此,我们需要明确提及它.
C++ takes the string literals as char[]
instead of taking it as string
. So we need to explicitly mention it.
std::cout << string("1") in vec << std::endl;
这篇关于模拟python的“输入"在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文