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

后端 未结 4 1415
盖世英雄少女心
盖世英雄少女心 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:51

    #include
    // #include
    #include
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
      const char *a[3]={"field1","field2","field3"};
    
      // If you want to create a brand new vector
      vector v(a, a+3);
      std::copy(v.begin(), v.end(), ostream_iterator(cout, "\n"));
    
      vector v2;
      // Or, if you already have an existing vector
      vector(a,a+3).swap(v2);
      std::copy(v2.begin(), v2.end(), ostream_iterator(cout, "\n"));
    
      vector 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(cout, "\n"));
    
    }
    

提交回复
热议问题