优化这段代码#include <iostream> #include <vector> #include <string> using namespace std; int main() { string s; s.reserve(100); char c; while (cin >> c) { s.push_back(c); } cout << "s===" << s << endl; return 0; }
时间: 2024-03-05 07:52:36 浏览: 195
这段代码的主要问题在于使用了大量的string操作,如果输入的数据量很大,会导致效率较低。可以使用字符数组来代替string,同时减少vector的使用,代码如下:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[100];
int len = 0;
char c;
while (cin >> c) {
s[len++] = c;
}
s[len] = '\0';
cout << "s===" << s << endl;
return 0;
}
```
这里使用了字符数组s来存储输入的字符,同时使用一个变量len来记录当前字符数组中已经存储的字符数。当输入一个字符时,将其存入字符数组s中,并将len加1。最后,将字符数组s的最后一个字符设置为'\0',以便输出时正确显示字符串。这样可以避免使用string的大量操作,从而提高了效率。
相关问题
#include <iostream> #include <vector> #include <string> #include <algorithm> #include <map> #include <thread> #include "List.h" #include "Node.h" using namespace std; int main(void) { auto* head = new Node<int>(10); //auto *list = new List<int>(head); List<int> list(head); //list->Display(); return 0; }
这段代码包含了 List 类和 Node 类的头文件,并且定义了一个 main 函数。在 main 函数中,它首先创建了一个 Node 对象 head,数据值为 10。然后,它使用 head 对象创建了一个 List 对象 list。最后,它调用了 List 类的成员函数 Display 输出链表中的元素。
需要注意的是,由于 List 类已经包含了头节点指针 _head 和链表长度 _size,因此没有必要再使用指针变量 list 来引用 List 对象。因此,可以直接使用 List<int> list(head) 来创建对象。另外,注释掉的 list->Display() 可以直接通过 list.Display() 来调用,因为 Display 函数是一个公有成员函数。
仅使用<iostream> #include <string> #include <cstdlib> #include <cstring> #include <cctype> #include <cmath> #include <cstdio> #include <cerrno> #include <clocale> #include <ctime> #include <cwchar> #include <cwctype> #include <iomanip> #include <numeric> #include <algorithm> #include <unistd.h> #include <sys/wait.h> #include <conio.h>库实现控制台填表式输入
### 控制台表格输入的实现方法
为了在控制台上实现类似于“填表”的功能,可以利用C++的标准库来处理用户的逐行输入并将其存储在一个二维数据结构中。这里推荐使用 `std::vector<std::string>` 来保存每一行的数据条目。以下是具体实现方式:
#### 表格输入的核心逻辑
通过循环不断请求用户输入每列的内容,并将这些内容按照行的形式存入容器之中。当完成所有必要字段的信息采集后,则停止收集流程并将结果打印出来或者继续其他业务逻辑操作。
```cpp
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Function to display table header dynamically based on column names provided by user or predefined ones.
void showTableHeader(const vector<string>& headers) {
cout << "+-----------------------------+\n"; // Fixed width for simplicity
cout << "| ";
for (const auto& hdr : headers) {
cout << setw(15) << left << hdr.substr(0, 15) << " | "; // Limit each field length to 15 chars
}
cout << "\n+-----------------------------+\n";
}
// Collecting data row-by-row from console until sentinel value entered ('done').
vector<vector<string>> collectDataRows(int numCols) {
vector<vector<string>> rows;
string cellValue;
int rowIndex = 0;
while (true) {
vector<string> currentRow(numCols);
cout << "Enter values for Row #" << ++rowIndex << ": \n";
for (int col = 0; col < numCols; ++col) {
cout << "Column [" << col + 1 << "] Value: ";
getline(cin >> ws, cellValue); // Use getline with manipulator to handle spaces correctly
if ("done" == cellValue && !rows.empty()) {
return rows; // If 'done', exit collection only after at least one valid entry exists.
}
currentRow[col] = move(cellValue);
if (!cellValue.empty() && all_of(cellValue.begin(), cellValue.end(), ::isspace)) {
throw invalid_argument("Empty cells not allowed.");
}
}
rows.emplace_back(move(currentRow));
}
}
// Display collected data in tabular format similar to how it was inputted earlier.
void printDataTable(const vector<string>& headers, const vector<vector<string>>& body) {
showTableHeader(headers);
for (const auto& rowData : body) {
cout << "| ";
for (size_t i = 0; i < rowData.size(); ++i) {
cout << setw(15) << left << rowData[i].substr(0, 15) << " | ";
}
cout << endl;
}
cout << "+-----------------------------+" << endl;
}
int main() try {
const int NUM_COLUMNS = 3; // Example number of columns
cout << "Welcome! Let's create a simple table.\nSpecify three-column entries below:\n";
vector<string> columnNames {"Name", "Age", "Occupation"};
showTableHeader(columnNames);
auto dataTable = collectDataRows(NUM_COLUMNS);
printDataTable(columnNames, dataTable);
} catch (exception& e) {
cerr << "Error occurred during execution: " << e.what() << ". Exiting..." << endl;
return EXIT_FAILURE;
}
```
此代码片段展示了如何构建一个基本但灵活的命令行界面用于录入多行列信息[^3]。它首先定义了一些辅助函数用来展示头部和实际记录部分;接着提供了核心算法让用户能够反复提交新的项目直至他们决定终止会话为止。最后还加入了异常处理器以便更好地应对潜在错误状况的发生。
---
###
阅读全文
相关推荐
















