0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C++でcsv fileを要素数指定なしの2D vectorに格納する方法の備忘録

Last updated at Posted at 2022-02-17

1D vectorであれば要素数指定なしで以下のようにpush_backすれば、自動的に要素数の上限が増えていくので、初期化時に要素数の上限指定なしで大丈夫。

{1,2,3,4,5,6,7,8,9,...}
C++
vector<string> vec1D;
vec1D.push_back(strbuf);

2D vectorの場合、中に入っている要素vectorの要素指定なしでは、いくつかひっかかったところがあった。

{ {1,2,3,...},
  {1,2,3,...},
  {1,2,3,...},
  {.........} }
  1. 以下のように始めに空の1D vectorを追加しないと、index out of rangeになる。

    C++

vector> vec2D;
vec2D.push_back(vector());
```

  1. 以下の方法で要素数を指定して、push_backしないと追加されない。
C++
vec2D.at(i).push_back(strbuf);

サンプルコード

要素指定は.at()を使いましょう。。。

vec2D.at(i).at(j)
C++
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <time.h>
#include <vector>
#include <regex>

using namespace std;

auto split = [](string src, auto pat){
    vector<string> result{};
    regex reg{pat};
    copy(
        sregex_token_iterator{src.begin(), src.end(), reg, -1},
        sregex_token_iterator{},
        back_inserter(result)
    );
    return result;
};

int main(int argc, char *argv[]){
 
  const char delimiter = ',';//カンマ区切り
  long long i = 0;
  string input_csv_file_path  = argv[1];
  ifstream ifs_csv_file(input_csv_file_path);
  string str_line_buf;
  str_line_buf.reserve(1000);
  string str_sep_buf;
  vector<vector<string>> vec2D;//csvファイルの中身を格納する2D vector, 容量指定なし
 
  while (getline(ifs_csv_file, str_line_buf)){
      i = 0;
      istringstream line_sep(str_line_buf);
      while (getline(line_sep, str_sep_buf, delimiter)){
        //始めに空vectorを追加するため、例外処理を挟む
        try{
          vec2D.at(i).push_back(str_sep_buf);//2D vectorのi番目の要素に文字列を追加する
        }catch(out_of_range& e){
          cerr << "Out of Range: " << e.what() << endl;
          vec2D.push_back(vector<string>());//始めに追加する場合は、空の1D vectorを追加する
          vec2D.at(i).push_back(str_sep_buf);
        }
        ++i;
      }
  }
  //標準出力
  for (long long j = 0; j < vec2D.size(); j++) {
      for (long long k = 0; k < vec2D[j].size(); k++) {
          cout << vec2D[j][k] << endl; //j=row number, k=column number;
      }
  }
}

まとめ

C++でcsvファイルをreadして、要素数指定なしの2D vectorに格納する方法を紹介した。より簡潔な方法を知れば更新していく。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?