繁体   English   中英

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

[英]copying c array of strings into vector of std::string

我需要将 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();
}
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"));

}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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