gpt4 book ai didi

c++ - 在 C++ 中动态引用不同类型的变量?

转载 作者:行者123 更新时间:2023-12-05 00:51:01 31 4
gpt4 key购买 nike

在这里,我想将我的 c++ 代码从版本 2 简化到版本 1。在 Python 这样的语言中,引用不同类型的变量(如版本 1)很简单。如何在 c++ 中实现类似的代码?

#include <iostream>
#include <vector>

/* version 1: compile failed */
void display(std::vector<int> vi, std::vector<double> vd) {
// error: operands to ?: have different types
// ‘std::vector<double>’ and ‘std::vector<int>’
auto& v = vi.empty() ? vd : vi;
for (const auto &e : v) {
std::cout << e << " ";
}
}

/* version 2 */
void display(std::vector<int> vi, std::vector<double> vd) {
if (!vi.empty()) {
for (const auto &e : vi) {
std::cout << e << " ";
}
} else {
for (const auto &e : vd) {
std::cout << e << " ";
}
}
}



int main(int argc, char *argv[]) {
std::vector<int> vi{0, 1, 2};
std::vector<double> vd{10., 11, 12};

// one of vi, vd can be empty after some modifications
...

display(vi, vd);
return 0;
}

补充:

这里的打印功能只是一个例子。我的主要目的是创建对 std::vector<int> 的引用或 std::vector<double>根据它们是否为空。下面的例子可能

#include <iostream>
#include <vector>

void process_1(std::vector<int> v) {
for (const auto &e : v) {
std::cout << e << " ";
}
std::cout << std::endl;
}

void process_1(std::vector<double> v) {
double sum = 0;
for (const auto &e : v) {
sum += e;
}
std::cout << sum << std::endl;
}

void process_2(std::vector<int>) {
//...
}

void process_2(std::vector<double>) {
//...
}

/* Version 2 */
int version_2(int argc, char *argv[]) {
std::vector<int> vi{0, 1, 2};
std::vector<double> vd{10., 11, 12};

if (!vi.empty()) {
process_1(vi);
} else {
process_1(vd);
}

// do something

if (!vi.empty()) {
process_2(vi);
} else {
process_2(vd);
}

return 0;
}

/* Version 1 */
int version_1(int argc, char *argv[]) {
std::vector<int> vi{0, 1, 2};
std::vector<double> vd{10., 11, 12};

// in Python, it's easy to create a reference dynamically, eg:
// ref = vd is len(vi) == 0 else vi
auto &ref = vd if vi.empty() else vi;

process_1(ref);
// do something
process_2(ref);

return 0;
}

最佳答案

大概是这样的:

void display(const std::vector<int>& vi, const std::vector<double>& vd) {
auto print_sequence = [](const auto& v) {
for (const auto &e : v) {
std::cout << e << " ";
}
}
vi.empty() ? print_sequence(vd) : print_sequence(vi);
}

关于c++ - 在 C++ 中动态引用不同类型的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73139116/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com