我最近從 c 切換到 c ,只是無法弄清楚我在這里做錯了什么。我想通過另一個函式訪問和設定地圖的成員。
這是我的示例,如果您愿意,您可以將其復制到 cpp.sh 左右
#include <iostream>
#include <map>
using namespace std;
struct test{
int i;
int j;
};
void addValues(test* val){
if (val == NULL){
val = new test();
cout<<"new";
}
val->i = 10;
val->j = 12;
}
void printVal(test* val){
cout<<"finish " << val->i << " " << val->j;
}
int main()
{
map<string, test*> bla = {{"test1",NULL}};
addValues(bla.at("test1"));
printVal(bla.at("test1"));
return 0;
}
我的專案中的代碼有點復雜,但基本上就是這個問題。我在 addValues() 中創建了一個測驗并且沒有洗掉它。為什么我不能在 printVal() 中列印這個值?我錯過了什么?
提前致謝!
uj5u.com熱心網友回復:
引數按值傳遞。指標也不例外。傳遞addValuesa 時,您會修改指標的本地副本nullptr。修改該本地副本不會影響地圖中的指標。通過參考傳遞指標:
void addValues(test*& val){
if (val == nullptr){
val = new test();
cout<<"new";
}
val->i = 10;
val->j = 12;
}
或者更好的是,首先不要使用原始指標。此外,考慮撰寫一個建構式來初始化 的成員,test而不是依賴呼叫者來初始化它們。
uj5u.com熱心網友回復:
例子 :
#include <iostream>
#include <map>
//using namespace std; NO teach yourself not to do this.
struct test
{
int i = 0; // <== in c you can initialize values of structs
int j = 0;
};
// this instead of printVal
std::ostream& operator<<(std::ostream& os, const test& t)
{
os << "i = " << t.i << ", j = " << t.j << "\n";
return os;
}
int main()
{
std::map<std::string, test> map =
{
{"test1",{1,1}},
{"test2",{2,2}},
};
// loop over all entries in the map
// range based for loop.
// each entry in the map is a key,value pair (not they key, not the value but a pair)
// https://en.cppreference.com/w/cpp/language/range-for
std::cout << "range based for over keyvalue pairs\n";
for (const auto& kv : map)
{
// note kv.second is where we use operator<< from earlier.
std::cout << "Key : " << kv.first << ", value : " << kv.second << "\n";
}
std::cout << "\n";
// structured bindings make code more readable
// https://en.cppreference.com/w/cpp/language/structured_binding
std::cout << "range based for using structured bindings \n";
for (const auto& [key, value] : map)
{
std::cout << "Key : " << key << ", value : " << value <<"\n";
}
std::cout << "\n";
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/328479.html
標籤:C
