2011-06-10 85 views
2

我需要将c数组字符串的元素存储在向量中。将c字符串数组复制到std :: string向量中

基本上我需要将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(); 
} 
+2

你拥有了它++在两个地方。从其中之一删除++。 – Dialecticus 2011-06-10 14:23:36

+0

是的,你是对的。感谢:) – Vijay 2011-06-10 14:26:53

回答

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

你确定吗?这是倾销我的核心。请参阅我的编辑。 – Vijay 2011-06-10 14:21:31

+0

如何将包含指向字符串的指针的c数组直接转换为std :: string? – Vijay 2011-06-10 14:23:47

+0

请参阅此处列出的第三个构造函数:http://www.cplusplus.com/reference/stl/vector/vector/以及文章底下示例中的“第五个向量”。 – yasouser 2011-06-10 14:28:37

5
std::vector<std::string> blah(a, a + LENGTH_OF_ARRAY) 
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")); 

} 
+0

+1部分'矢量(a,a + 3).swap(v2);'。 – Nawaz 2011-06-10 14:28:42

相关问题