2013-08-18 28 views
1

我遇到了我的方法問題。我希望它接受一個字符串數組作爲它的第一個參數,而不是一個向量字符串。但是,當我嘗試使用一個字符串數組並在主函數中創建一個時,我會得到各種錯誤。我不知道是否應該爲我的參數或字符串使用一個指向字符串數組的指針。任何幫助?向量與C++中的數組

#include <cstdio> 
#include <cstring> 
#include <cmath> 
#include <algorithm> 
#include <vector> 
#include <map> 
#include <set> 
#include <string> 
#include <sstream> 
#include<iostream> 
using namespace std; 
class UserName 
{ 
    public: 
    string newMember(string* exist, string newname) { 
    bool found = false; 
    bool match = false; 
    stringstream ss; 
    string result; 
    string othername; 
    for(int i = 0; i < exist.size(); i++){ 
     if(exist[i] == newname){ 
      found = true; 
     break; 
     } 
    } 
    if(found){ 
     for(int x = 1; ; x++){ 
      match = false; 
     ss.str(""); 
     ss << newname << x; 
     for(int i = 0; i < exist.size();i++){ 
      //cout << ss.str() << endl; 
      othername = ss.str(); 
      if(exist[i] == othername){ 
       match = true; 
      break; 
      } 
     } 
     if(!match){ 
      result = ss.str(); 
      break; 
     } 
     } 
     return result; 
    } 
    else return newname; 
    } 
}; 
int main(){ 
    UserName u; 
    string Database [4]; 
    Database[0] == "Justin"; 
    Database[1] == "Justin1"; 
    Database[2] == "Justin2"; 
    Database[3] == "Justin3"; 
    cout << u.newMember(Database, "Justin") << endl; 
    return 0; 
} 
+0

錯誤消息是你的朋友。 – keyser

+0

我編輯了正確的代碼。我發佈了錯誤的版本 – user2510809

回答

4

使用類似以下內容:

std::string Database[] ={ "Justin", "Justin1", "Justin2","Justin3" };

newmember作爲

string newMember(std::string exist[], std::size_t n, string newname)

取代exist.size()n

main

cout << u.newMember(Database, 4,"Justin") << endl;

此外,按您的編輯

操作=是不一樣的操作者==,第一個是一個賦值運算符(分配處的值其右邊的變量)另一個==是平等運算符

所以你需要使用:

Database[0] = "Justin"; 
Database[1] = "Justin1"; 
Database[2] = "Justin2"; 
Database[3] = "Justin3"; 
6

C++中的數組很不幸是一種特殊情況,並且在很多方面並不像正確的值。舉幾個例子:

void foo(int c[10]); // looks like we're taking an array by value. 
// Wrong, the parameter type is 'adjusted' to be int* 

int bar[3] = {1,2}; 
foo(bar); // compile error due to wrong types (int[3] vs. int[10])? 
// No, compiles fine but you'll probably get undefined behavior at runtime 

// if you want type checking, you can pass arrays by reference (or just use std::array): 
void foo2(int (&c)[10]); // paramater type isn't 'adjusted' 
foo2(bar); // compiler error, cannot convert int[3] to int (&)[10] 

int baz()[10]; // returning an array by value? 
// No, return types are prohibited from being an array. 

int g[2] = {1,2}; 
int h[2] = g; // initializing the array? No, initializing an array requires {} syntax 
h = g; // copying an array? No, assigning to arrays is prohibited 

(從here拍攝)

如果你想表現得像一個適當的值使用std::array數組。

#include <array> 
#include <string> 

void foo(std::array<std::string, 10> arr) { /* ... */ } 

int main() { 
    std::array<std::string, 10> arr = {"Justin", "Justin1", "Justin2", "Justin3"}; 
    foo(arr); 
}