copying c array of strings into vector of std::string

后端 未结 4 1392
盖世英雄少女心
盖世英雄少女心 2020-12-21 12:02

I need to store elements of a c array of strings in a vector.

Basically I need to copy all the elements of a c array into a vector.

相关标签:
4条回答
  • 2020-12-21 12:41
    std::vector<std::string> blah(a, a + LENGTH_OF_ARRAY)
    
    0 讨论(0)
  • 2020-12-21 12:41

    You use the insert method to add content to a vector. Take a look at the sample fragment from here: http://www.cplusplus.com/reference/stl/vector/insert/

    0 讨论(0)
  • 2020-12-21 12:51
    #include<vector>
    // #include<conio.h>
    #include<iostream>
    #include <iterator>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
      const char *a[3]={"field1","field2","field3"};
    
      // If you want to create a brand new vector
      vector<string> v(a, a+3);
      std::copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));
    
      vector<string> v2;
      // Or, if you already have an existing vector
      vector<string>(a,a+3).swap(v2);
      std::copy(v2.begin(), v2.end(), ostream_iterator<string>(cout, "\n"));
    
      vector<string> v3;
      v3.push_back("field0");
      // Or, if you want to add strings to an existing vector
      v3.insert(v3.end(), a, a+3);
      std::copy(v3.begin(), v3.end(), ostream_iterator<string>(cout, "\n"));
    
    }
    
    0 讨论(0)
  • 2020-12-21 12:58
    std::vector<std::string> fields(a, a + 3);
    
    0 讨论(0)
提交回复
热议问题