我正在尝试制作一个项目,询问有关酒店访问的一些问题并重复回答,非常简单.到目前为止,我有这个代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
int df;
int days;
string bed;
string bn;
cout << "Welcome to C++ Hotel, we have to ask you a few questions about your stay in order to give you the correct rate." << endl;
cout << "First, what floor would you like to stay on? (We currently have rooms available from floors 2 to 12)" << endl;
cin >> df;
while (df > 12 && 2 < df){
cout << …Run Code Online (Sandbox Code Playgroud) 我试图遍历一个向量(k),并检查它是否包含一个值(键),如果是,我想添加在不同向量(val)的相同索引处找到的值,然后添加任何值在那里找到第三个向量(temp).
for(int i = 0; i < k.size(); ++i)
{
if(k.at(i) == key)
{
temp.push_back(val.at(i));
}
}
Run Code Online (Sandbox Code Playgroud)
我最近学到了很多,但我仍然没有超级高级的C++,这段代码确实适用于我的目的,但它非常慢.它可以处理大小为10或100的小向量,但对于大小为1000,10000甚至1000000的大小需要花费太长时间.
我的问题是,有更快更有效的方法吗?
我试过这个:
std::vector<int>::iterator it = k.begin();
while ((iter = std::find(it, k.end(), key)) != k.end())
{
int index = std::distance(k.begin(), it);
temp.push_back(val.at(index));
}
Run Code Online (Sandbox Code Playgroud)
我想也许使用矢量迭代器可以加快速度,但由于bad_alloc错误,我不能让代码工作,我不知道如何修复.
有谁知道我能做些什么,使这个代码有点多快?
我收到这个错误:
error: cannot convert 'std::string {aka std::basic_string<char>}' to 'char*' for argument '1' to 'char* strcpy(char*, const char*)'
Run Code Online (Sandbox Code Playgroud)
我假设它意味着它无法将我的一个标题字符串分配给我的newtitle字符串,因为它们的类型不同.(我认为一个是char和另一个const char?)
strcpy(title, newtitle);
Run Code Online (Sandbox Code Playgroud)
但它们都被定义为类型字符串,所以我有点困惑的是它给了我这个错误是什么.虽然我错误地认为这个错误意味着什么.
#include<iostream>
#include<iomanip>
using namespace std;
#include <cstring>
class Movie{
private:
string title;
int year;
string director;
public:
void setTitle(string); // function prototype
void setYear(int); // function prototype
void setDirector(string); // function prototype
void displayMovie(); // function prototype
};
void Movie::setTitle(string newtitle)
{
strcpy(title, newtitle);
}
int main()
{
Movie myMovie;
string movietitle;
cout << "Enter the title of …Run Code Online (Sandbox Code Playgroud)