C++에서 Void 함수 사용

Jinku Hu 2023년10월12일
  1. void함수를 사용하여 더 긴 문자열 찾기
  2. void함수를 사용하여지도에 키가 있는지 확인
  3. void함수를 사용하여 벡터의 요소 정렬
C++에서 Void 함수 사용

이 기사에서는 C++에서void함수를 사용하는 방법에 대한 여러 가지 방법을 보여줍니다.

void함수를 사용하여 더 긴 문자열 찾기

반환 값이없는 함수에는 반환 매개 변수로 지정된void유형이 있습니다. void함수에서 암시 적return문은 함수 본문의 마지막 문 다음에 호출됩니다. 명시 적return문은 제어 흐름을 즉시 호출자 함수로 이동해야하는void함수 본문에 배치 할 수 있습니다. 다음 예에서isLessString함수는 콘솔에 해당 문자열을 인쇄하는 유일한 조건문을 포함하며 그 뒤에 암시 적return이 실행됩니다.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

using std::cout;
using std::endl;
using std::map;
using std::string;
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함수를 사용하여지도에 키가 있는지 확인

이 경우void기능을 사용하여std::map컨테이너에 대한 키 검색 기능을 구현합니다. 결과는cout스트림에 해당 문자열 상수를 인쇄하여 전달됩니다. 이것은 프로그램에서 내부적으로 데이터를 전달하는 데 선호되는 방법은 아니지만 최종 사용자에게 정보를 표시하는 데 사용할 수 있습니다.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

using std::cout;
using std::endl;
using std::map;
using std::string;
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함수를 사용하여 벡터의 요소 정렬

또는vector객체를 참조로 사용하고 해당 요소를 오름차순으로 정렬하는std::sort알고리즘에 대한 래퍼 함수를 ​​구현할 수 있습니다. void함수는 일반적으로 호출자 함수에 실패를 알리는 수단이 없기 때문에 솔루션을 설계 할 때 항상 고려해야합니다.

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

using std::cout;
using std::endl;
using std::map;
using std::string;
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;
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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 Facebook

관련 문장 - C++ Function