将c数组的字符串复制到std :: string的向量中

时间:2011-06-10 14:14:52

标签: c++ vector

我需要在向量中存储c数组字符串的元素。

基本上我需要将c数组的所有元素复制到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();
}

有人可以帮我把c数组元素存储到向量中吗?

修改

以下代码正在倾销核心!!请帮忙

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();
}

4 个答案:

答案 0 :(得分:12)

std::vector<std::string> fields(a, a + 3);

答案 1 :(得分:5)

std::vector<std::string> blah(a, a + LENGTH_OF_ARRAY)

答案 2 :(得分: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"));

}

答案 3 :(得分:0)

使用insert方法向向量添加内容。看看这里的示例片段: http://www.cplusplus.com/reference/stl/vector/insert/