2011-06-10 59 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

相關問題