gpt4 book ai didi

c++ - c++ 中的 vector 与数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:24 26 4
gpt4 key购买 nike

我的方法有问题。我希望它接受一个字符串数组作为它的第一个参数,而不是一个 vector 字符串。但是,当我尝试使用字符串数组并在主函数中创建一个时,我会遇到各种错误。我不知道我是否应该为我的参数使用一个指向字符串数组的指针,或者只是一个字符串。有帮助吗?

#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;
}

最佳答案

不幸的是,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);
}

关于c++ - c++ 中的 vector 与数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18299881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com