vtl*_*inh 6 c++ pointers std-pair
我不知道如何才能在C++中完成这项工作.
意图是:
pair<int, int> foo() {
if(cond) {
return std::make_pair(1,2);
}
return NULL; //error: no viable conversion from 'long' to 'pair<int, int>
}
void boo() {
pair<int, int> p = foo();
if (p == NULL) { //error: comparison between NULL and non-pointer ('int, int' and NULL)
// doA
} else {
int a = p.first;
int b = p.second;
// doB
}
}
Run Code Online (Sandbox Code Playgroud)
由于我不能在C++中使用return NULL,这是我的第二次尝试:
pair<int, int>* foo() {
if(cond) {
return &std::make_pair(1,2); //error: returning address of local temporary object)
}
return nullptr;
}
void boo() {
pair<int, int>* p = foo();
if (p == nullptr) {
// doA
} else {
int a = p->first;
int b = p->second;
// doB
}
}
Run Code Online (Sandbox Code Playgroud)
能够返回一对和空值的正确方法是什么.
Sho*_*hoe 10
你应该使用一个例外:
std::pair<int, int> foo() {
if(cond) {
return std::make_pair(1,2);
}
throw std::logic_error("insert error here");
}
Run Code Online (Sandbox Code Playgroud)
在你的boo功能:
try {
std::pair<int, int> p = foo();
int a = p.first;
int b = p.second;
} catch (std::logic_error const& e) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
而这里的活例子.
在替代方案中,您可以使用std::optional(从C++ 14开始)或boost::optional:
std::optional<std::pair<int, int>> foo() {
if(cond) {
return std::make_pair(1,2);
}
return {};
}
std::optional<std::pair<int, int>> p = foo();
if (p) {
int a = p->first;
int b = p->second;
} else {
// do something
}
Run Code Online (Sandbox Code Playgroud)
而这里的一个与增压版的工作示例.
尝试通过引用将一对传递给foo(),然后从该函数返回一个指示成功或失败的bool.像这样:
bool foo(pair<int, int>& myPair) {
if(cond) {
myPair = std::make_pair(1,2);
return true;
}
return false;
}
void boo() {
pair<int, int> myPair;
if (!foo(myPair)) {
// doA
} else {
int a = myPair.first;
int b = myPair.second;
// doB
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:根据你在做什么,你应该杀了foo()如果可能的话,评估cond中boo()
void boo() {
pair<int, int> myPair;
if (!cond) {
// doA
} else {
myPair = std::make_pair(1,2);
int a = myPair.first;
int b = myPair.second;
// doB
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8561 次 |
| 最近记录: |