在 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