C++에서 2차원 vector를 동적으로 할당하는 방법에 관한 질문입니다.

aeronova의 이미지

안녕하세요,
이번에는 vector를 이용하여 동적으로 2차원 배열의 크기를 정하는 방법에 관한 질문입니다.
일단 2차원 vector를 이용하여 matrix라는 type이 다음과 같이 정의되어 있습니다.

    typedef std::vector<double> Row;
    typedef std::vector<Row>    Matrix;

그리고 5 X 3 크기로 배열의 크기를 동적으로 할당했습니다.
(이미 size는 알고 있어서요.)

    // 5 by 3 matrix
    Matrix matrix;
    matrix.reserve(5);
    for(int i=0;i<5;i++) {
        matrix[i].reserve(3);
    }

근데 다음과 같이 살펴보니 뭔가 이상합니다.ㅜㅜ
    std::cout << matrix.size() << std::endl;
    std::cout << matrix[0].size() << std::endl;
    std::cout << matrix.capacity() << std::endl;
    std::cout << matrix[0].capacity() << std::endl;

결과는..
0
0
5
4294467537

일단 size가 둘다 0인 것은 이해가 갑니다. 공간만 5 X 3 으로 잡아두었지, 실제 안에 아무것도 없으니까요.
근데 이상한 것은 matrix[0].capacity()가 4294467537이 아니라 3이어야 하는데, 왜 그런지 모르겠습니다.
흠... 어떻게 해야 공간을 3으로 잡을 수 있을까요?
kewlbear의 이미지

matrix.size()가 0인데 matrix[0]를 써도 되나요?

doldori의 이미지

reserve()는 미리 메모리만 할당하는 것입니다.
vector에 원소를 추가하는 것이 아니므로 size는 변하지 않습니다.
reserve()와 원소 추가를 같이 하려면 resize()를 하세요.

    Matrix matrix;
    matrix.resize(5);
    for(int i=0;i<5;i++) {
        matrix[i].resize(3);
    }

아예 한 번에 5x3의 행렬을 만드려면 이렇게 해도 됩니다.
    Matrix matrix(5, Row(3));

Quote:

일단 size가 둘다 0인 것은 이해가 갑니다. 공간만 5 X 3 으로 잡아두었지, 실제 안에 아무것도 없으니까요.
근데 이상한 것은 matrix[0].capacity()가 4294467537이 아니라 3이어야 하는데, 왜 그런지 모르겠습니다.

이 결과는 정의되지 않습니다. matrix의 원소가 없는 상태에서 matrix[0]를 썼으니까요.
aeronova의 이미지

감사합니다. 말씀대로 resize를 사용하니 문제가 없네요.
앞으로 reserve와 resize의 차이를 잘 알고 써야 겠습니다. :)

It's better to burn out than to fade away. -- Kurt Cobain.

댓글 달기

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
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.