数组 - 循环遍历辅助阵列
Array- looping through secondary array
无法从第二个数组获取索引以匹配第一个数组
// array constants
const int people = 7;
const int phoneNumbers = 7;
int main() {
char person, family;
int index;
string found;
int size =7;
//array declaration and set values
string people [] ={"Darryl","Jasmine","Brian","Duane","Ayana","Mia","Maya"};
// const char phoneNumbers = 7;
string phoneNumbers[] = {"678-281-7649", "818-933-1158", "212-898-2022",
"361-345-3782","817-399-3750","313-589-0460","818-634-4660"};
//set boolean value
found = "False";
//initialize index
index = 0;
// search variable and user input
cout << "who are you looking for? " << endl;
cin >> people[index];
for (index=0; index<=6; index--) {
if (people[index] == people[index] )
cout << "phone num for " << people[index] << " is "<<
phoneNumbers[index] << endl;
}
return 0;
}
当我输入 Jasmine people[]
数组时,phoneNumbers[]
数组会带回phoneNumbers[]
的第一个索引,它应该带回phoneNumbers[]
数组上的第二个索引
这里有两个问题。
-
你正在用 cin 替换 people[0] 的内容 - 所以数组的第一项将始终是用户的输入。
-
你是递减指数,所以 FOR 循环转到索引 0,-1,-2...这是个问题,因为 C 和 C++ 中的数组从 0 变为上限值。
我更愿意添加一个变量:
string input;
然后:
cin >> input;
对于循环应使用:
for (index = 0; index < 6; index++)
在您的条件下,我会使用:
if (person[index] == input) ...
一个更简洁的方法就是使用C++标准模板库提供的std::map
。以下是我对您要实现的目标的看法:
// phoneNumber.cpp
#include <iostream>
#include <map>
int main()
{
// delcare a map variable that maps people's names to phone numbers
std::map <std::string,std::string> lookUpPhoneNumber = {
{"Darryl", "678-281-7649"},
{"Jasmine", "818-933-1158"},
{"Brian", "212-898-2022"},
{"Duane", "361-345-3782"},
{"Ayana", "817-399-3750"},
{"Mia", "313-589-0460"},
{"Maya", "818-634-4660"}
};
// take input name
std::string inputName;
// user prompt
std::cout << "who are you looking for?: ";
std::cin >> inputName;
// look up name in map
if(lookUpPhoneNumber.find(inputName) != lookUpPhoneNumber.end()){
std::cout << "Phone num for " << inputName << " is: " << lookUpPhoneNumber[inputName] << "n";
} else{
std::cout << "Name does not exist!n";
}
return 0;
}
若要编译和运行,请使用以下命令:
g++ -std=c++11 -o phoneNumber phoneNumber.cpp
./phoneNumber
或者检查编译器选项以启用c++11
标准或更高版本的编译。
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 遍历unordered_map向量
- 从预序遍历构造 bst 的 c++ 和 python 解决方案之间的区别
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 如何正确地推回然后遍历堆中对象的向量?
- 遍历二维数组的所有子数组
- 如何在可变参数模板函数中遍历可变参数元组?
- 如何遍历 2D 阵列?
- 数组 - 循环遍历辅助阵列
- 三维阵列遍历
- 创建一个二维向量阵列,遍历
- 如何大步遍历n维阵列
- 这是遍历阵列的更快方法