简体   繁体   中英

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

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<std::string> .

#include<vector>
#include<conio.h>
#include<iostream>

using namespace std;

int main()
{
    char *a[3]={"field1","field2","field3"};

    //Some code here!!!!

    vector<std::string>::const_iterator it=fields.begin();
    for(;it!=fields.end();it++)
    {
        cout<<*it++<<endl;
    }   
    getch();
}

Could anybody help me out to store c array elements into a vector?

EDIT

this below code is dumping the core!!Pls help

int main()
{
    char *a[3]={"field1","field2","field3"};
    std::vector<std::string> fields(a, a + 3);

    vector<std::string>::const_iterator it=fields.begin();
    for(;it!=fields.end();it++)
    {
        cout<<*it++<<endl;
    }   
    getch();
}
std::vector<std::string> fields(a, a + 3);
std::vector<std::string> blah(a, a + LENGTH_OF_ARRAY)
#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"));

}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM