在 C++ 中使用 void 函数
本文将演示有关如何在 C++ 中使用 void
函数的多种方法。
使用 void
函数查找更长的字符串
没有返回值的函数将 void
类型指定为返回参数。在 void
函数中,隐式的 return
语句在函数体的最后一条语句之后调用。注意,可以将显式的 return
语句放置在 void
函数主体中,在该主体中,控制流需要立即移至调用方函数。在下面的示例中,isLessString
函数包含将条件字符串打印到控制台的唯一条件语句,并在其后执行隐式 return
。
#include <iostream>
#include <algorithm>
#include <iterator>
#include <map>
using std::cout; using std::endl;
using std::string; using std::map;
using std::vector;
void isLessString(string &s1, string &s2)
{
s1.size() < s2.size() ?
cout << "string_1 is shorter than string_2" << endl:
cout << "string_2 is shorter than string_1" << endl;
}
int main() {
string str1 = "This string has arbitrary contents";
string str2 = "Another string with random contents";
isLessString(str1, str2);
return EXIT_SUCCESS;
}
输出:
string_1 is shorter than string_2
使用 void
函数查找 map 中是否存在键
在这种情况下,void
函数可用于实现 std::map
容器的关键字搜索功能。注意,通过将相应的字符串常量打印到 cout
流来传达结果。尽管这不是在程序内部传递数据的首选方法,但可将其用于指示信息给最终用户。
#include <iostream>
#include <algorithm>
#include <iterator>
#include <map>
using std::cout; using std::endl;
using std::string; using std::map;
using std::vector;
void keyExistsInMap(map<string, string> &m, const string& key)
{
m.find(key) != m.end() ?
cout << "Key exists in a map" << endl :
cout << "Key does not exist in a map" << endl;
}
int main() {
map<string, string> veggy_map = {{"a", "Ali",},
{"m", "Malvo",},
{"p", "Pontiac",},
{"s", "Sensi",}};
keyExistsInMap(veggy_map, "s");
keyExistsInMap(veggy_map, "x");
return EXIT_SUCCESS;
}
输出:
Key exists in a map
Key does not exist in a map
使用 void
函数对向量中的元素进行排序
或者,可以为 std::sort
算法实现包装函数,该包装函数以 vector
对象为参考,并以升序对元素进行排序。请注意,void
函数通常缺乏将故障传达给调用者函数的方法,因此在设计解决方案时应始终考虑这一点。
#include <iostream>
#include <algorithm>
#include <iterator>
#include <map>
using std::cout; using std::endl;
using std::string; using std::map;
using std::vector;
void sortVector(vector<string> &vec)
{
std::sort(vec.begin(), vec.end(),
[] (const auto &x, const auto &y) {return x < y;});
}
int main() {
vector<string> arr = { "element", "implementation", "or", "the",
"execution", "dependent", "template", "character",
"that", "all", "via", "class" };
sortVector(arr);
for (const auto &item : arr) {
cout << item << "; ";
}
cout << endl;
return EXIT_SUCCESS;
}
输出:
all; character; class; dependent; element; execution; implementation; or; template; that; the; via;
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn