C++ STL 이용 에러 체크 (map에서의 insert나 erase)는 어떻게 하시나요?

nyulnim의 이미지

STL을 이용해서 구현을 하다보면 에러 체크를 어떻게 할지 애매한 경우가 많습니다.

map에서

#include <map>
iterator insert( iterator pos, const TYPE& pair );
void insert( input_iterator start, input_iterator end );
pair<iterator,bool> insert( const TYPE& pair );

를 쓰는 경우에 리턴 타입이 void인 경우나, pair 이런 경우
어떻게 에러 체크를 해야 하는지요?

실제로 insert나 erase를 수행한 후에
대상이 된 원소가 map안에 존재하는지 find로 찾아보고 에러체크를 해야 하나요?

아니면 try-catch구문으로 에러를 체크하시나요?

winner의 이미지

pair의 second는 성공여부를 나타냅니다. void일 경우는 find 후 insert 하는 두번의 검색시간이 부담으로 느껴지신다면 find의 반환 iterator를 insert를 할 때 hint로 적용시키는 또다른 insert member 함수가 있을 겁니다. 그걸 쓰면 그 위치에서 인접한 부분부터 삽입위치를 찾기 때문에 수행시간이 적게 걸리죠.
try-catch로 하고 싶다면 적절한 exception을 throw하는 wrapper를 작성하시는 것이 맞습니다.

imyejin의 이미지

C++ 표준러이브러리에서 컨테이너나 알고리듬의 설계방식은 지우거나 집어넣거나 하는 동작을 하기 전에 그 동작이 제대로 이루어질 수 있는지 검사하거나 해당 원소를 찾는 것으로 가정합니다. 따라서 라이브러리 설계 의도대로 그러한 검사를 먼저 하고 나서 집어넣거나 지우거나 해야지 일단 넣거나 지우기부터 해보고 에러가 나나 안나나 검사하겠다는 방법으로 접근하면 자연스럽게 프로그래밍을 할 수 없습니다.

단, 아래 분 말씀대로 pair를 돌려주는 함수의 경우는 pair에 성공 실패 여부 bool형이 들어가 있죠.

임예진 팬클럽 ♡예진아씨♡ http://cafe.daum.net/imyejin

[예진아씨 피카사 웹앨범] 임예진 팬클럽 ♡예진아씨♡ http://cafe.daum.net/imyejin

nyulnim의 이미지

감사한 답변들을 통해서 제가 제대로 이해를 하고 있는지
테스트 코드를 작성해 보았습니다.
이래저래 검색을 해봐도, map의 insert가 성공적으로 되었는지
검사를 하는 예제는 별로 없는 것 같네요. ^^

#include <stdio.h>
#include <map>
#include <string>
 
 
int main(int argc, char *argv[])
{
 
    map<int, string>                        mmNames;
    map<int, string>::iterator              iter;
    pair<map<int, string>::iterator, bool>  ret;
 
 
    iter = mmNames.find(1);
    if(iter!=mmNames.end())
    {
        printf("\nmmNames contains 1");
    }
    else
    {
        printf("\nmmNames does not contains 1");
    }
 
 
    ret = mmNames.insert(map<int, string>::value_type(1, string("Lee")));
    if(ret.second == true)
    {
        printf("\ninsert success");
    }
    else
    {
        printf("\ninsert fail");
    }
 
    iter = mmNames.find(1);
    if(iter!=mmNames.end())
    {
        printf("\nmmNames contains 1");
    }
    else
    {
        printf("\nmmNames does not contains 1");
    }
 
    return(0);
}

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.