2

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();
}
joce
  • 9,624
  • 19
  • 56
  • 74
Vijay
  • 65,327
  • 90
  • 227
  • 319

4 Answers4

13
std::vector<std::string> fields(a, a + 3);
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • how can a c array which holds the pointers to the strings can be directly converted to std::string? – Vijay Jun 10 '11 at 14:23
  • See the third constructor listed here: http://www.cplusplus.com/reference/stl/vector/vector/ and also the `vector fifth` in the example beneath the article. – yasouser Jun 10 '11 at 14:28
6
std::vector<std::string> blah(a, a + LENGTH_OF_ARRAY)
James
  • 24,676
  • 13
  • 84
  • 130
John
  • 2,395
  • 15
  • 21
2
#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"));

}
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

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/

holtavolt
  • 4,378
  • 1
  • 26
  • 40